Reputation: 59
I'm kinda new to Swift. I have this problem, where the SpriteNode "Ball" is not reacting to applyImpulse command in touchesBegan-method. The overall physicsBody works totally fine, gravity, restitution etc. But nothing is happening, when I use applyImpulse. Here's the code:
var ball = SKSpriteNode()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.physicsWorld.gravity = CGVectorMake(0.0, -9.81)
// Add the ball
ball = SKSpriteNode(imageNamed: "Ball")
ball.setScale(2.0)
ball.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
ball.zPosition = 100.0
// Physics of the ball
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.height / 2)
ball.physicsBody?.allowsRotation = true
ball.physicsBody?.dynamic = true
ball.physicsBody?.usesPreciseCollisionDetection = true
ball.physicsBody?.mass = 2.0
ball.physicsBody?.restitution = 0.8
ball.physicsBody?.velocity = CGVectorMake(0.0, 5.0)
self.addChild(ball)
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
self.ball.physicsBody?.applyImpulse(CGVectorMake(0.0, 5.0))
}
Please help me :)
Obviously I have a ground too, this is just the relevant code.
Upvotes: 2
Views: 169
Reputation: 3405
You create local object ball with this line of code:
let ball = SKSpriteNode(imageNamed: "Ball")
inside didMoveToView
method. It created and placed to scene with self.addChild(ball)
. But in this line of code:
self.ball.physicsBody?.applyImpulse(CGVectorMake(0.0, 5.0))
you call physicsBody?.applyImpulse(CGVectorMake(0.0, 5.0))
from other ball
object which is not represented in the code that you posted here. And this object is not the same object you created in didMoveToView
method.
You need to init your global for this function ball
object in your didMoveToVeiw
:
ball = SKSpriteNode(imageNamed: "Ball")
without let
keyword
Upvotes: 1