我正在使用Swift和SpriteKit。
我有以下情况:
这里,每个"三角形"是一个SKShapenode。 我的问题是,我想检测有人触摸屏幕时触摸的是哪个三角形。 我假设所有这些三角形的hitbox都是矩形,所以我的函数会返回我触摸的所有hitbox,而我只想知道实际触摸了哪一个。
有没有办法让hitbox与形状完全匹配而不是矩形?
这是我目前的代码:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
let touch = touches.first
let touchPosition = touch!.locationInNode(self)
let touchedNodes = self.nodesAtPoint(touchPosition)
print(touchedNodes) //this should return only one "triangle" named node
for touchedNode in touchedNodes
{
if let name = touchedNode.name
{
if name == "triangle"
{
let triangle = touchedNode as! SKShapeNode
// stuff here
}
}
}
}
答案 0 :(得分:2)
您可以尝试CGPathContainsPoint
使用SKShapeNode
代替nodesAtPoint
,这更合适:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
let touch = touches.first
let touchPosition = touch!.locationInNode(self)
self.enumerateChildNodesWithName("triangle") { node, _ in
// do something with node
if node is SKShapeNode {
if let p = (node as! SKShapeNode).path {
if CGPathContainsPoint(p, nil, touchPosition, false) {
print("you have touched triangle: \(node.name)")
let triangle = node as! SKShapeNode
// stuff here
}
}
}
}
}
答案 1 :(得分:1)
这是最简单的方法。
locks
答案 2 :(得分:0)
我使用Swift 4的方式:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let touchPosition = touch.location(in: self)
let touchedNodes = nodes(at: touchPosition)
for node in touchedNodes {
if let mynode = node as? SKShapeNode, node.name == "triangle" {
//stuff here
mynode.fillColor = .orange //...
}
}
}