SpriteKit physics applyImpulse in direction

孤者浪人 提交于 2021-01-29 15:01:49

问题


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


回答1:


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];


来源:https://stackoverflow.com/questions/24971726/spritekit-physics-applyimpulse-in-direction

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