suraj kandel
suraj kandel

Reputation: 11

move an object (spritenode) in swift continously until touched on the screen

i am trying to get an object to perform an action continuously until it is touched, but when touched the object just performs the action once.
this is what i have got to so far

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    for touches: AnyObject in touches {

        plane.physicsBody?.velocity = CGVectorMake(0, 0)
        plane.physicsBody?.applyImpulse(CGVectorMake(0, 500))
    }
}

any sugessiton how to get it working.

Upvotes: 1

Views: 378

Answers (1)

Christian
Christian

Reputation: 22343

If you want to move an object, you better use SKAction.moveBy instead of an impulse. At the moment you only execute that action if the user touched the screen. If you want to run an action until the user touches the screen, you have to put it in the didMoveToView method and use a key so you can remove the action from the sprite:

class YourClass: SKScene{
    var sprite = SKSpriteNode()

    override func didMoveToView(view: SKView) {

        //4 seconds for 500y
        var neededTime:NSTimeInterval = 4
        var action = SKAction.moveBy(CGVectorMake(0, 500), duration: neededTime)
        var repeatAction = SKAction.repeatActionForever(action)



        //Repeat the action forever and with a key so you can remove it on touch:
        sprite.runAction(repeatAction, withKey: "aKey")
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        //remove the action
        sprite.removeActionForKey("aKey")
    }
}

Upvotes: 1

Related Questions