SpriteKit move rotated physicsBody with applyImpulse

后端 未结 2 1758
半阙折子戏
半阙折子戏 2021-01-15 06:14

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

相关标签:
2条回答
  • 2021-01-15 06:36

    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)];
    
    0 讨论(0)
  • 2021-01-15 06:41

    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)];
    }
    
    0 讨论(0)
提交回复
热议问题