我的游戏有3 SKSpriteNodes
,用户可以使用touchesBegan
和touchesMoved
移动。但是,当用户移动nodeA
并通过另一个名为nodeB
的节点时,nodeB
会跟随nodeA
,依此类推。
我创建了一个SKSpriteNodes
数组,并使用了for-loop
来简化生活。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let nodes = [nodeA, nodeB, nodeC]
for touch in touches {
let location = touch.location(in: self)
for node in nodes {
if node!.contains(location) {
node!.position = location
}
}
}
}
一切正常,除非nodeA
正在移动,且nodeB
,nodeB
的交叉路径跟随nodeA
。
如何设置,以便当用户移动时nodeA
和nodeA
通过nodeB
nodeB
不会跟随nodeA
。
答案 0 :(得分:5)
不是进行慢速搜索,而是为触摸的节点设置一个特殊的节点变量
class GameScene
{
var touchedNodeHolder : SKNode?
override func touchesBegan(.....)
{
for touch in touches {
guard touchNodeHandler != nil else {return} //let's not allow other touches to interfere
let pointOfTouch = touch.location(in: self)
touchedNodeHolder = nodeAtPoint(pointOfTouch)
}
}
override func touchesMoved(.....)
{
for touch in touches {
let pointOfTouch = touch.location(in: self)
touchedNodeHolder?.position = pointOfTouch
}
}
override func touchesEnded(.....)
{
for touch in touches {
touchedNodeHolder = nil
}
}
}
答案 1 :(得分:1)
经过一些实验,我找到了解决这个问题的方法。
我没有通过触摸位置选择节点,而是发现通过名称属性选择节点就可以了。
显示的代码在touchesMoved和touchesBegan方法
中实现//name of the nodes
let nodeNames = ["playO", "playOO", "playOOO", "playX", "playXX", "playXXX"]
//the actual nodes
let player = [playerO, playerOO, playerOOO, playerX, playerXX, playerXXX]
for touch in touches {
let pointOfTouch = touch.location(in: self)
let tappedNode = atPoint(pointOfTouch)
let nameOfTappedNode = tappedNode.name
for i in 0..<nodeNames.count {
if nameOfTappedNode == nodeNames[i] {
z += 1
player[i]!.zPosition = CGFloat(z)
print(player[i]!.zPosition)
player[i]!.position = pointOfTouch
}
}
}