[英]How to detect precisely when a SKShapeNode is touched?
I'm working with Swift and SpriteKit. 我正在使用Swift和SpriteKit。
I have the following situation : 我有以下情况:
Here, each of the "triangles" is a SKShapenode. 在此,每个“三角形”都是一个SKShapenode。 My problem is that I would like to detect when someone touches the screen which triangle is being touched. 我的问题是我想检测何时有人触摸屏幕上正在触摸哪个三角形。 I assume that the hitbox of all these triangles are rectangles so my function returns me all the hitboxes touched while I only want to know which one is actually touched. 我假设所有这些三角形的点击框都是矩形,因此我的函数将返回我触摸过的所有点击框,而我只想知道实际触摸了哪一个。
Is there any way to have a hitbox that perfectly match the shape instead of a rectangle ? 有没有什么办法可以使形状完全匹配而不是矩形的命中盒呢?
Here's my current code : 这是我当前的代码:
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
}
}
}
}
You could try to use CGPathContainsPoint
with a SKShapeNode
instead of nodesAtPoint
, which is more appropriate: 您可以尝试将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
}
}
}
}
}
This would be the easiest way of doing it. 这将是最简单的方法。
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
for touch in touches {
let location = touch.locationInNode(self)
if theSpriteNode.containsPoint(location) {
//Do Whatever
}
}
}
The way I do this with Swift 4: 我使用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 //...
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.