Sprite Kit - Apply Impulse to shoot projectile at character

社会主义新天地 提交于 2019-11-30 14:53:53

The basic steps are

  1. Calculate vector components from the projectile launcher to the bird
  2. Normalize the components (optional)
  3. Create a vector by scaling the (normalized) components
  4. Apply impulse to the projectile using the vector

Here's an example of how to do that

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!