简体   繁体   中英

Ball dropping animation not working (Swift)

This code is supposed to drop a ball from the top of the screen to the bottom. And once it touches the bottom of the screen, it should appear back to the top of the screen. It doesn't relocate to the top and it stops moving. I want it to be a continuous loop that resets the ball.y position every time it touches the bottom.

import SpriteKit

class GameScene: SKScene {
    let ball = SKShapeNode(circleOfRadius: 20)
    let label = SKLabelNode(fontNamed: "Futura")
    let movingObjects = SKSpriteNode()

    override func didMoveToView(view: SKView) {
        let sceneBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
        self.physicsBody = sceneBody

        //Ball Transition
        let ballTransition = SKAction.sequence([SKAction.fadeInWithDuration(1)])
        ball.runAction(ballTransition)

        //Ball function
        ball.fillColor = SKColor.redColor()

        ball.physicsBody = SKPhysicsBody(circleOfRadius: 25)
        ball.physicsBody?.affectedByGravity = false

        //Ball Movement
        ball.position = CGPoint(x: self.frame.size.width/2, y: CGFloat(self.frame.size.height*1))

        ballMovement()

        movingObjects.addChild(ball)

        self.addChild(label)
    }

    func ballMovement() {
        let moveBall = SKAction.moveToY(self.frame.size.height*0, duration: 3)
        let removeBall = SKAction.removeFromParent()
        let moveAndRemove = SKAction.sequence([moveBall, removeBall])
        ball.runAction(moveAndRemove)

        //Label Sprite
        label.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
        label.fontColor = SKColor.redColor()
        label.fontSize = 30
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
        label.text = "\(ball.position.y)"

        if ball.position.y < 26 {
            ball.position = CGPoint(x: self.frame.size.width/2, y: CGFloat(self.frame.size.height*1))
        }
    }
}

removing the ball from its parent within the action and still acting on it elsewhere is going to become very fragile as your program gets more complex. Why not just do it all with the actions and let sprite kit worry about it ?

 let moveBall = SKAction.moveToY(0, duration: 3)
 let goBackUp = SKAction.moveToY(self.frame.size.height, duration:0)
 let keepFalling = SKAction.sequence([moveBall, goBackUp])
 ball.runAction(SKAction.repeatActionForever(keepFalling))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM