将触摸检测限制在图像精灵的遮罩区域的正确方法是什么?
下面的代码是(理论上)我希望它如何工作。它是一个大型的彩色块,掩盖着宇宙飞船的形状。当用户触摸时,我想只有被遮罩的部分响应触摸。在下面的代码中,事件被忽略(可能因为cropNode.maskNode是属性,而不是子项)。我尝试过其他方法,但没有一个限制触摸屏蔽区域。
问题是......这个应该怎么做?
override func didMoveToView(view: SKView) {
let cropNode = SKCropNode();
let mostlyHiddenSprite = SKSpriteNode(color: SKColor.yellowColor(), size: CGSize(width: 300,height: 300))
cropNode.addChild(mostlyHiddenSprite)
cropNode.maskNode = TouchableMask(texture: spaceShipTexture, color: nil, size: mostlyHiddenSprite.size)
self.userInteractionEnabled = true
cropNode.position = CGPoint(x: 400, y: 200)
self.addChild(cropNode)
println("try to touch the masked portion");
}
class TouchableMask: SKSpriteNode {
override init (texture: SKTexture?, color: UIColor?, size: CGSize) {
super.init(texture: texture, color: color, size: size)
self.userInteractionEnabled = true
self.zPosition = 999
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
println("Mask was touched.");
}
}
谢谢! 弗兰克
答案 0 :(得分:2)
好的,所以我被自己困住了。我解决了这个问题。
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.location(in: self)
if(mask.contains(location))
{
//this will work only if the touch is in the mask.
}
}}