Search code examples
iossprite-kittouchesbegan

Applying forces on an object


If i've understood right, when i "applyForce" it is pushing my object in my vector direction and power for as long as the applyForce is applied. but when i try to apply force on a body in 'touchesBegan' (because i want it to pushed up as long as i touch the screen) all i get is a little push that makes it jump for few pixels and then it falls down as a result of the physicsWorld settings. (I also want the force stop pushing when 'touchesEnded') ideas anybody? Thanks

(Xcode 5, spriteKit)


Solution

  • touchesBegan: will only fire once when the screen is touched.

    To continue to do something for as long as your finger is touching the screen you can do something like this:

    Create a BOOL ivar

    @implementation MyScene
    {
        BOOL theFingerTouches;
    }
    

    Next register the touch as you already know how

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        theFingerTouches = true;
    }
    

    Make sure to also register when the touch is no longer present

    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
        theFingerTouches = false;
    }
    

    Lastly use the update: method to do what you need depending on your BOOL

    -(void)update:(CFTimeInterval)currentTime
    {
        if(theFingerTouches == true)
        {
            // some code here
        }
    }