SpriteKit move rotated physicsBody with applyImpulse

喜欢而已 提交于 2019-12-19 10:46:26

问题


I want to move a physicsBody with the applyImpulse method in a direction based on the physicsBody rotation.

Foe example, the physicsBody is a square in shape, I call a "move" which will apply an impulse to make it move up vertically. I then call a method to rotate the physicsBody 45 degrees right. If I call the "move" method again, the physicsBody will move diagonally right and up.

Can anyone help please?


回答1:


I suggest that you follow Sprite Kit’s coordinate and rotation conventions. Specifically, your sprite image should be facing right at zero degrees (the default value), and a positive value is a counter-clockwise rotation. That said, here's one way to apply an impulse in the direction a sprite is facing:

// Specify the force to apply to the SKPhysicsBody
CGFloat r = 5;

// Create a vector in the direction the sprite is facing
CGFloat dx = r * cos (sprite.zRotation);
CGFloat dy = r * sin (sprite.zRotation);

// Apply impulse to physics body
[sprite.physicsBody applyImpulse:CGVectorMake(dx,dy)];



回答2:


UPDATED:

Fixed with the below thanks to @0x141E

-(void)characterJump {

    CGFloat radianFactor = 0.0174532925;
    CGFloat rotationInDegrees = _body.zRotation / radianFactor;
    CGFloat newRotationDegrees = rotationInDegrees + 90;
    CGFloat newRotationRadians = newRotationDegrees * radianFactor;

    CGFloat r = 500;

    CGFloat dx = r * cos(newRotationRadians);
    CGFloat dy = r * sin(newRotationRadians);

    [_body.physicsBody applyImpulse:CGVectorMake(dx, dy)];
}


来源:https://stackoverflow.com/questions/25628811/spritekit-move-rotated-physicsbody-with-applyimpulse

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