如何使用Spritekit和Swift根据水龙头上下移动球?

时间:2015-06-29 00:48:29

标签: swift sprite-kit

我的touchesBegan方法的代码是:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let moveBall = SKAction.moveToY(380, duration: 0.4)
    let moveBalldown = SKAction.moveToY(293, duration: 0.4)
    if ball.position.y == 293 {
        ball.runAction(moveBall)
    }
    if ball.position.y == 380 {
        ball.runAction(moveBalldown)
    }

当我点按屏幕时,没有任何反应。

我希望球根据水龙头上下移动。

球应该在第一次点击时向上移动,然后在y = 380时向下移动,然后再次点击屏幕。

以下是影响球的其余代码。

var ball = SKSpriteNode(imageNamed: "ball")

self.ball.position = CGPoint(x:40, y:293)
self.addChild(self.ball)
self.ball.yScale = 0.17
self.ball.xScale = 0.17

self.physicsWorld.gravity = CGVectorMake(0, 0)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height * 0.08)
ball.physicsBody?.dynamic = true

var degreeRotation = CDouble(self.SBEBSpeed) * M_PI / 180
self.ball.zRotation -= CGFloat(degreeRotation)

let moveBall = SKAction.moveToY(380, duration: 0.4)
let moveBalldown = SKAction.moveToY(293, duration: 0.4)
if ball.position.y == 293 {
    ball.runAction(moveBall)
}
if ball.position.y == 380 {
    ball.runAction(moveBalldown)
}

1 个答案:

答案 0 :(得分:0)

但有一些事情。确保在didMoveToView函数中添加球。为了保持清洁,我已经为addBall()创建了一个函数。

他们想要移动你不需要物理的球,所以我把它留在了这个解决方案之外。

我已经使touchesBegan函数只有一个if语句用于两种可能性。

我希望这适合你!我试过这个,它对我有用。

import SpriteKit

class GameScene: SKScene {

    var ball = SKSpriteNode(imageNamed: "ball")

    override func didMoveToView(view: SKView) {

        // Make sure you have this function here
        addBall()
    }

    func addBall() {

        self.ball.position = CGPoint(x: 40, y: 293)
        self.ball.yScale = 0.17
        self.ball.xScale = 0.17

        self.addChild(self.ball)

    }

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

        let moveBall = SKAction.moveToY(380, duration: 0.4)
        let moveBalldown = SKAction.moveToY(293, duration: 0.4)

        // If the position of the ball is not 293 it will move to 293, otherwise it will move to 380
        if ball.position.y == 293 {
            self.ball.runAction(moveBall)
        } else {
            self.ball.runAction(moveBalldown)
        }
    }
}