gpt4 book ai didi

swift - 节点不动

转载 作者:搜寻专家 更新时间:2023-10-31 22:05:31 24 4
gpt4 key购买 nike

( swift 3)

import SpriteKit
import GameplayKit

class GameScene: SKScene {
var object = SKSpriteNode()

override func didMove(to view: SKView) {

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

}

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

for touch in touches {
let location = touch.location(in: self)
object.run(SKAction.move(to: location, duration: 0.3))

}

}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)

object.run(SKAction.move(to: location, duration: 0.3))


}
}

override func update(_ currentTime: TimeInterval) {




}
}

此代码旨在允许我在场景周围拖动一个“点”,但是......我就是做不到!它不会让步!我在网上看过,但找不到任何东西。我尝试将这段代码粘贴到一个新项目中,它在那里工作,但即使删除和替换我的“点”节点似乎也对我的主项目没有帮助。

那么……有什么想法吗?

最佳答案

Confused 已经说完了您必须了解的关于您的问题的一切。我尝试添加有助于您编写代码的详细信息。首先,当您使用 self.childNode(withName 搜索节点时,您应该使用可选绑定(bind),这样如果该节点不存在,您的项目就不会崩溃。然后,正如 Confused 所解释的那样,您应该在调用操作之前添加控件,以确保您的操作尚未运行。下面我举个例子:

import SpriteKit
class GameScene: SKScene {
var object = SKSpriteNode.init(color: .red, size: CGSize(width:100,height:100))
override func didMove(to view: SKView) {
if let sprite = self.childNode(withName: "//dot") as? SKSpriteNode {
object = sprite
} else { //dot not exist so I draw a red square..
addChild(object)
}
object.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
}
func makeMoves(_ destination: CGPoint) {
if object.action(forKey: "objectMove") == nil {
object.run(SKAction.move(to: destination, duration: 0.3),withKey:"objectMove")
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
makeMoves(location)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
makeMoves(location)
}
}
}

输出:

enter image description here

关于swift - 节点不动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41658088/

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