gpt4 book ai didi

swift - Sprite 不会用手指/SpriteKit/Swift 3 移动

转载 作者:行者123 更新时间:2023-11-28 08:22:09 25 4
gpt4 key购买 nike

*我搜索了大部分地方都找不到我问题的“基本解决方案”

您好,我正在尝试创建一个简单的 SKSpriteNode,它将随着我的手指在屏幕上的任何位置移动(x 和 y 坐标)。到目前为止,我所做的是下面的代码,我似乎无法弄清楚其他东西,因为我的 Sprite 在游戏运行时甚至不会移动。我也在以下位置收到错误:

simpleS = self.childNode(withName: "simpleS") as! SKSpriteNode

这行代码导致我的程序无法运行,因为我添加了它。请并感谢您的帮助。

在这种情况下,Sprite“simpleS”是我在触摸开始时尝试移动的 Sprite。

代码从这里开始:

    import SpriteKit
import GameplayKit

class GameScene: SKScene {

var simpleS = SKSpriteNode()

override func didMove(to view: SKView) {

simpleS = self.childNode(withName: "simpleS") as! SKSpriteNode

simpleS.physicsBody?.affectedByGravity = true
}



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

for touch in touches {
let location = touch.location(in: self)

simpleS.run(SKAction.moveTo(x: location.x, duration: 0.0))
simpleS.run(SKAction.moveTo(y: location.y, duration: 0.0))

}

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

for touch in touches {
let location = touch.location(in: self)

simpleS.run(SKAction.moveTo(x: location.x, duration: 0.0))
simpleS.run(SKAction.moveTo(y: location.y, duration: 0.0))

}
}
}

最佳答案

这段代码

simpleS = self.childNode(withName: "simpleS") as! SKSpriteNode

将 GameScene.sks 中的 Sprite 与 GameScene.swift 连接起来因此,在第一步中,您必须确保在 sks 文件中设置正确的名称(确切地说是“simpleS”)。

如果您做对了,请将错误发送给我们。我已经构建并运行了您的代码,一切正常。

另一点是,如果你想让你的 Sprite 只通过你的手指移动,你必须删除 touchesBegan 函数中的代码,因为 touchesBegan 会在你触摸的任何地方移动你的 Sprite 。

关于swift - Sprite 不会用手指/SpriteKit/Swift 3 移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40969497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com