Karl Johan Vallner
Karl Johan Vallner

Reputation: 4300

SpriteKit physics applyImpulse in direction

I am using the spriteKit-s physics engine. I have 2 objects on the screen, (say player and enemy). Now I am trying to use the applyImpulse method on enemy, which is supposed to pull it towards the player.

CGFloat radians = [Utilites pointPairToBearingDegrees:self.enemy.position 
                                          secondPoint:self.player.position];
CGVector vector = CGVectorMake(500*cosf(radians), 500*sinf(radians));
[self.enemy.physicsBody applyImpulse:vector];

However this applies force in wierd directions. Not consistent at all. Anyone have a clue why?

Ps. the radians are calculated correctly!!!

Thanks

Upvotes: 0

Views: 795

Answers (1)

0x141E
0x141E

Reputation: 12753

Try this...

CGFloat dx = self.player.position.x - self.enemy.position.x;
CGFloat dy = self.player.position.y - self.enemy.position.y;

CGFloat mag = sqrt(dx*dx+dy*dy);

CGVector vector = CGVectorMake(dx/mag*kImpulseScale, dy/mag*kImpulseScale);
[self.enemy.physicsBody applyImpulse:vector];

Upvotes: 3

Related Questions