ryohei ryohei - 6 months ago 11
Swift Question

Why the speed of a node is getting faster and faster when a button is pressed in spritekit?

As the title suggests, every time I tap a button node, an item node gets faster. How am I able to keep the speed consistent? This is the code for the function.

let ball: Ball = Ball(textureName: "ball.png")
func attackButton() {

ball.removeFromParent()

ball.position = CGPointMake(100, hero.position.y)
ball.startMoving()
hero.throwBall() // for just movement of his arm
playThrowSound()
addChild(ball)

}

func startMoving() {
let moveLeft = SKAction.moveByX(200, y: 0, duration: 3)
ball.runAction(SKAction.repeatActionForever(moveLeft))

let rotating = SKAction.rotateByAngle(CGFloat(M_PI), duration: 6)
ball.runAction(SKAction.repeatActionForever(rotating))
}


Also, though this code works, but not in my desired way. After a ball is produced, the ball is deleted and the next ball is produced. I know this is because of the removeFromParent(), but I cannot figure out other ways. I want that once produced ball to be deleted only when it is off the screen.

So I really appreciate if you give me solutions for those two problems.

Answer

Could you add the code for your Ball-Class? I guess that in your Ball-Class is the Problem for your app crashing. In the function attackButton you are removing and adding the ball to the Scene. But i think in your Ball-Class you are adding a SKNode but you don't remove it there, too. So the code below should work if you fixed the Problem in your Ball-Class (you did not post the Code - so you have to check that yourself).

let ball: Ball = Ball(textureName: "ball.png")

func attackButton() {
    ball.removeFromParent()
    ball.position = CGPointMake(100, hero.position.y)
    hero.throwBall() // for just movement of his arm
    playThrowSound()
    addChild(ball)
    ball.startMoving()
}

func startMoving() {
    ball.removeAllActions()
    let moveLeft = SKAction.moveByX(200, y: 0, duration: 3)
    ball.runAction(SKAction.repeatActionForever(moveLeft))

    let rotating = SKAction.rotateByAngle(CGFloat(M_PI), duration: 6)
    ball.runAction(SKAction.repeatActionForever(rotating))
}
Comments