我正在使用以 swift 编写的 sprite 工具包为 iOS 创建游戏。我在屏幕上有一堆 SKSpriteNode 可以拖来拖去。它们是各种形状,例如人、苹果、书等。问题是,假设人在苹果前面,但您可以通过人图像 (png) 中的透明像素看到人后面的苹果。当你去触摸苹果来移动它时,这个人会因为那些透明像素而不是苹果而被选中。
如果 SKSpriteNode 的像素是透明的,我该如何制作不响应触摸的 SKSpriteNode?p>
最佳答案
如果你想选择一个被另一个 Sprite 部分隐藏的 Sprite ,你可以使用nodesAtPoint:CGPoint
获取用户触摸下的节点数组。然后您可以遍历数组中的节点以查找并选择最接近触摸点的节点。下面是一个简单的示例,说明如何在 Swift 中执行此操作:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches.first as? UITouch {
let location = touch.locationInNode(self)
var closest:CGFloat?
let nodes = nodesAtPoint(location)
for node in nodes as! [SKNode] {
if let sprite = node as? SKSpriteNode {
// Calculate the distance from the node to the touch
let dx = location.x - node.position.x
let dy = location.y - node.position.y
let distance = dx*dx + dy*dy
// Find the closest
if closest == nil || distance < closest! {
closest = distance
selected = sprite
}
}
}
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if let sprite = selected {
if let touch = touches.first as? UITouch {
let location = touch.locationInNode(self)
sprite.position = location
}
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
selected = nil
}
下面是一段使用上述代码通过触摸移动的形状:
关于ios - 如果像素是透明的,如何制作不响应触摸的 SKSpriteNode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950525/