J Norris J Norris - 4 months ago 9
Swift Question

Touch Sprite, make it jump up then fall down again and again

I created a project where I have a ball and when the view loads, it falls down, which is good. I'm trying to get the ball to jump back up and fall down again when the Spritenode is tapped.

This is what is Not working (I tried this on the simulator and tapped the ball immediately. It bounced once, but then went straight down.)

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


firstBall.userInteractionEnabled = true


for touch: AnyObject in touches {
let location = touch.locationInNode(self)

if(firstBall.containsPoint(location)) {
firstBall.physicsBody?.velocity = CGVectorMake(0, 600)
firstBall.physicsBody?.applyImpulse(CGVectorMake(0, 1100))
}
}


Before I put this in, I tried to use this(below) and it worked when you tapped anywhere except the spritenode

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


firstBall.userInteractionEnabled = true

firstBall.physicsBody?.velocity = CGVectorMake(0, 0)
firstBall.physicsBody?.applyImpulse(CGVectorMake(0, 1100))

}


This code allowed it to work when you tapped anywhere on the screen, except the ball. Every time you tapped the screen, the ball jumped.


How do I make the sprite node jump up in place when it is tapped.(version 7.3.1)


If you need any more information, please comment what you would like to see and I will edit the post asap.

Thanks, Jordan

Answer

I tested your code and it seems that using firstBall.userInteractionEnabled = true is the cause. Without it, it should work. I did some research (here for example), but can't figure out what's the reason of this behavior with userInteractionEnabled. Or for what reason do you use userInteractionEnabled?