Search code examples
swiftrotationsprite-kitskphysicsbody

Angular Impulses


So I'm using angular impulses to rotate a sprite with a physicsBody. I want one side of the screen to apply an impulse in one direction, whilst the other side of the screen will apply an impulse in the other direction (see code below).

 override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

    // Defines UI Touch //
    let touch = touches.first as UITouch!
    let touchPosition = touch.locationInNode(self)


    // Left or Right movement based on touch //
    if touchPosition.x < CGRectGetMidX(self.frame) {sprite.physicsBody?.applyAngularImpulse(-10)}
    else {sprite.physicsBody?.applyAngularImpulse(10)}

    // Smooths motion
    let rate: CGFloat = 0.5; //Controls rate of motion. 1.0 instantaneous, 0.0 none.
    let relativeVelocity: CGVector = CGVector(dx:angularVelocity-sprite.physicsBody!.velocity.dx, dy:0);
    sprite.physicsBody!.velocity=CGVector(dx:sprite.physicsBody!.velocity.dx+relativeVelocity.dx*rate, dy:0);

}

Only problem is, obviously if you press left side of screen, then right side of screen... It cancels out the impulses and stops the sprite.

My question is, how can I change my above code so that it does not cancel and instead the impulse is applied full power the opposite direction?

I know that this is easily achieved by having relativeVelocity as 0 but I can't work out how to have this value as 0 without a conflict between 'int' and 'CGVector'

Any help much appreciated!


Solution

  • You may want to set angularVelocity to 0 before applying the opposite angular impulse. Here's the example:

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    
        // Defines UI Touch //
        let touch = touches.first as UITouch!
        let touchPosition = touch.locationInNode(self)
    
        // Left or Right movement based on touch //
        if touchPosition.x < CGRectGetMidX(self.frame) {
            sprite.physicsBody?.angularVelocity = 0
            sprite.physicsBody?.applyAngularImpulse(-10)
        } else {
            sprite.physicsBody?.angularVelocity = 0
            sprite.physicsBody?.applyAngularImpulse(10)
        }        
    }