【问题标题】:Set a x position to a SKSpriteNode将 x 位置设置为 SKSpriteNode
【发布时间】:2016-12-22 06:35:21
【问题描述】:

您好,我正在开发一个简单的积木游戏。游戏是这样的。

在这张图片的底部,您可以看到一个桨(黄色条)。在 touchesBegan 上,我想获取触摸的 x 位置并将拨片移动到该 x 位置。

我试过了,但遇到了错误。

2016-12-21 14:35:50.540 BrickOut[1347:38411] SKUtil.m: MGGetBoolAnswer 在模拟器中不可用。

X 位置:(95.0, 670.33332824707)

致命错误:在展开可选值 (lldb) 时意外发现 nil

Swift 代码

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    var ball:SKSpriteNode!
    var paddle:SKSpriteNode!

    override func didMove(to view: SKView) {
        ball = self.childNode(withName: "Ball") as! SKSpriteNode!
        paddle = self.childNode(withName: "Paddle") as! SKSpriteNode!


        ball.physicsBody?.applyImpulse(CGVector(dx: 50, dy: 50))
        let border = SKPhysicsBody(edgeLoopFrom: (view.scene?.frame)!)
        border.friction = 0
        self.physicsBody=border

    }



    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        for touch in touches{
            let touchLocation = touch.location(in: self.view)
            print("X Location : ", touchLocation)
            paddle.position.x = touchLocation.x

        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches{

            let touchLocation = touch.location(in: self.view)
            print("X Location moved: ", touchLocation)
            paddle.position.x = touchLocation.x

        }
    }

}

谁能帮我解决这个问题。我想把桨的x位置改成触摸的x位置。

【问题讨论】:

  • if let ball = self.childNode(withName: "//Ball") as? SKSpriteNode { ball.physicsBody?.applyImpulse(CGVector(dx: 50, dy: 50)) }
  • 虽然您在 GameScene 文件中缺少 sprite 节点

标签: ios swift skspritenode


【解决方案1】:

首先你可以忽略这个

2016-12-21 14:35:50.540 BrickOut[1347:38411] SKUtil.m:MGGetBoolAnswer 在模拟器中不可用。

接下来,在这些行中

ball = self.childNode(withName: "Ball") as! SKSpriteNode!
paddle = self.childNode(withName: "Paddle") as! SKSpriteNode!

你应该投到SKSpriteNode而不是SKSpriteNode!

现在再次运行......你刚刚在加载场景时发生了崩溃,对吧?

这意味着在您的 sks 中,您没有放置一个名为 BallSKSpriteNode 和/或另一个名为 PaddleSKSpriteNode

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多