Sprite Kit - Apply Momentum for Shooting Outside

I am developing a game using Sprite-Kit (Objective-C). This is a game in which you control a bird in flight, and arrows and other bad shells shoot at you from the right / top / bottom sides of the screen. I use physics instead of SKAction to accomplish this, as I want it to seem as viable as possible. Therefore, I know how to use Impulse on a projectile to shoot a bird at it, but I wonder how it can be guaranteed that the projectile will be shot directly at the bird, regardless of the position of the y-bird and the y-positioning of the projectile before using Impulse?

I have a very frustrating time for this, so any help on this will be greatly appreciated. Thank.

+4
source share
1 answer

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

// 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)
+8
source

All Articles