如果像素是透明的,如何制作不响应触摸的SKSpriteNode? [英] How do I make a SKSpriteNode that does not respond to touch if it's pixels are transparent?

查看:139
本文介绍了如果像素是透明的,如何制作不响应触摸的SKSpriteNode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



如何制作一个不响应的SKSpriteNode触摸它的像素是否透明?

解决方案

如果你想选择一个被另一个精灵部分隐藏的精灵,你可以使用


I am creating a game for iOS using sprite kit written in swift. I have a bunch of SKSpriteNode on a screen that can be dragged around. They are various shapes such as a person, an apple, a book etc. The problem is, say the person is in front of the apple but you can see the apple behind the person through the transparent pixels in the persons image (png). When you go to touch the apple to move it, the person gets selected because of those transparent pixels instead of the apples.

How do I make a SKSpriteNode that does not respond to touch if it's pixels are transparent?

解决方案

If you want to select a sprite that is partially hidden by another sprite, you can use nodesAtPoint:CGPoint to obtain an array of nodes that are under the user's touch. You can then iterate over the nodes in the array to find and select the node closest to the touch point. Here's a quick example of how to do that in 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
}

Here's a clip of shapes being moved by touch with the above code:

这篇关于如果像素是透明的,如何制作不响应触摸的SKSpriteNode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆