如何使用SpriteKit根据水龙头上下移动球?

时间:2015-06-25 23:29:19

标签: ios swift cocoa-touch sprite-kit

我的触摸开始功能的代码就是:

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)

我有一段时间没有触及SpriteKit,但我想测试你的代码。我目前正在运行XCode版本6.3.1,我看到他们已经更新了touchesBegan函数,现在需要一组NSObject。但是你在方法中的实际代码运行得很好,所以只要你设置了" ball"在最初渲染时到正确的坐标。这是我的工作示例:

import SpriteKit

class GameScene: SKScene {

var ball = SKSpriteNode()

override func didMoveToView(view: SKView) {
    var ballTexture = SKTexture(imageNamed: "ball.png")
    ball = SKSpriteNode(texture: ballTexture)
    ball.position = CGPoint(x: CGRectGetMidX(self.frame), y: 293)

    self.addChild(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 ball.position.y == 293 {
        ball.runAction(moveBall)
    }
    if ball.position.y == 380 {
        ball.runAction(moveBalldown)
    }
}

编辑:(因为我还没有发表评论,而且我不想做出新答案)我在更新后运行了你的代码并且球甚至没有出现在我的屏幕上。当你说什么都没发生时,这会发生在你身上吗?唯一的问题是x位置。我建议使用相对于self.frame

的坐标
相关问题