Reputation: 15
this is my first post here and i am new to iOS programming. I am using Xcode 8 and Swift 3 to build my practice game. All i want is i want to jump the ball when the screen is tapped but the impulse is not working. Here is the code i have written.
class GameScene: SKScene {
var footBall = SKSpriteNode(imageNamed: "sfb")
var Score = 0
var GameStarted = false
override func didMove(to view: SKView) {
self.removeAllChildren()
self.anchorPoint = CGPoint(x: 0.0, y: 0.0)
footBall.size = CGSize(width: 100, height: 100)
footBall.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
footBall.physicsBody = SKPhysicsBody(circleOfRadius: footBall.frame.height / 2)
footBall.physicsBody?.affectedByGravity = false
footBall.physicsBody?.allowsRotation = true
footBall.physicsBody?.isDynamic = true
self.addChild(footBall)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if(GameStarted == false){
GameStarted = true
footBall.physicsBody?.affectedByGravity = true
footBall.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
footBall.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 90))
}
else{
footBall.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
footBall.physicsBody?.applyForce(CGVector(dx: 0, dy: 90))
}
}
override func update(_ currentTime: TimeInterval) {
}
When clicked the velocity of the ball becomes zero for a moment but the impulse should drive it up which is not happening. Please help me through this and ignore any ignorance because this is my first question and i am new to this.
Upvotes: 1
Views: 184
Reputation: 1167
Please note that in the true branch you are applying a force, not an impulse.
Change:
footBall.physicsBody?.applyForce(CGVector(dx: 0, dy: 90))
to
footBall.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 90))
Don't understand why you always zero the velocity either.
Upvotes: 1