简体   繁体   English

落球动画不起作用(Swift)

[英]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. 我希望它是一个连续的循环,每次触到底部时都会重置ball.y位置。

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 ? 为什么不只用动作来做所有事情,而让Sprite Kit担心呢?

 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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