我正在使用 Sprite-Kit (Objective-C) 开发游戏。在这款游戏中,你控制一只飞行中的小鸟,箭和其他不好的射弹会从屏幕的右/上/下侧向你射击。我使用物理而不是 SKAction 来完成此任务,因为我希望它看起来尽可能逼真。所以我知道在射弹上使用 applyImpulse 将其射向鸟,但我想知道的是如何保证射弹将直接射向鸟,无论鸟的 y 定位和 y 定位如何applyImpulse 之前的射弹?
我在完成这项工作时经历了非常令人沮丧的时间,因此我们将非常感谢有关此事的任何帮助。谢谢。
基本步骤是
- 计算从射弹发射器到鸟的矢量分量
- 标准化组件(可选)
- 通过缩放(标准化)分量创建向量
- 使用矢量对射弹施加冲量
这是如何执行此操作的示例
Obj-C
// Calculate vector components x and y
CGFloat dx = bird.position.x - launcher.position.x;
CGFloat dy = bird.position.y - launcher.position.y;
// Normalize the components
CGFloat magnitude = sqrt(dx*dx+dy*dy);
dx /= magnitude;
dy /= magnitude;
// Create a vector in the direction of the bird
CGVector vector = CGVectorMake(strength*dx, strength*dy);
// Apply impulse
[projectile.physicsBody applyImpulse:vector];
Swift
// Calculate vector components x and y
var dx = bird.position.x - launcher.position.x
var dy = bird.position.y - launcher.position.y
// Normalize the components
let magnitude = sqrt(dx*dx+dy*dy)
dx /= magnitude
dy /= magnitude
// Create a vector in the direction of the bird
let vector = CGVector(dx:strength*dx, dy:strength*dy)
// Apply impulse
projectile.physicsBody?.applyImpulse(vector)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)