ios - 如何使用 SpriteKit 根据点击来上下移动球?

标签 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)
    }

最佳答案

我有一段时间没有接触过 SpriteKit,但我想测试你的代码。我当前正在运行 XCode 版本 6.3.1,并且我看到他们已经更新了 TouchBegan 函数,现在采用一组 NSObject。但是方法内的实际代码运行得很好,因此只要您在最初渲染时将“球”设置为正确的坐标即可。这是我的工作示例:

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

的坐标

关于ios - 如何使用 SpriteKit 根据点击来上下移动球?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062481/

相关文章:

从 firebase 快速加载图像

ios - 不在 set updateConstraints 中时,UIStackView 间距会打破约束

ios - 如何在touchesMoved :?中获取最低View

ios - 将苹果 iAd 添加到应用程序更新中

ios - 为什么 UITableViewCell detailTextLabel 在 Swift 中是可选的而 textLabel 不是

iOS - 改变每个 AVAssetTrack 的音量

iphone - 为 NSURLRequest 创建 cookie?

ios - 内置联系人应用程序是否有自定义 URL 方案?

ios - 无法在 WatchOS 3 中更新 Apple Watch 并发症

ios - 键盘打开时移动 View 的问题