ios - 如果像素是透明的,如何制作不响应触摸的 SKSpriteNode?

标签 ios iphone swift ipad sprite-kit

我正在使用以 swift 编写的 sprite 工具包为 iOS 创建游戏。我在屏幕上有一堆 SKSpriteNode 可以拖来拖去。它们是各种形状,例如人、苹果、书等。问题是,假设人在苹果前面,但您可以通过人图像 (png) 中的透明像素看到人后面的苹果。当你去触摸苹果来移动它时,这个人会因为那些透明像素而不是苹果而被选中。

如果 SKSpriteNode 的像素是透明的,我该如何制作不响应触摸的 SKSpriteNode?

最佳答案

如果你想选择一个被另一个 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
}

下面是一段使用上述代码通过触摸移动的形状:

enter image description here

关于ios - 如果像素是透明的,如何制作不响应触摸的 SKSpriteNode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950525/

相关文章:

objective-c - swift 错误 : Cannot convert value of type '() throws -> ()' to specified type 'Bool'

iOS 应用商店版权拒绝

ios - SWIFT 2 - UICollectionView - 慢速滚动

ios - IAP或Authorize.net

ios - Swift 中的prepareForSegue 正在更改passAlongID 和passAlongRow 的值

iphone - 呈现 MFMailComposeViewController,但它在可见后立即消失

ios - 使用 Swifter Framework 快速检索 Twitter 用户图像和名称

iphone - 如何使用音频队列服务在 iPhone 应用程序中以立体声播放单声道文件

iphone - 核心数据切片绘图样式

ios - 在表格 View 中滚动时图像重复单元格