Main steps
- Calculate vector components from gun launcher to bird
- Normalize components (optional)
- Creating a vector by scaling (normalized) components
- Apply momentum to projectile using vector
Here is an example of how to do it.
Obj-c
CGFloat dx = bird.position.x - launcher.position.x;
CGFloat dy = bird.position.y - launcher.position.y;
CGFloat magnitude = sqrt(dx*dx+dy*dy);
dx /= magnitude;
dy /= magnitude;
CGVector vector = CGVectorMake(strength*dx, strength*dy);
[projectile.physicsBody applyImpulse:vector];
Swift
var dx = bird.position.x - launcher.position.x
var dy = bird.position.y - launcher.position.y
let magnitude = sqrt(dx*dx+dy*dy)
dx /= magnitude
dy /= magnitude
let vector = CGVector(dx:strength*dx, dy:strength*dy)
projectile.physicsBody?.applyImpulse(vector)
source
share