如何检测是否已触摸 SKSpriteNode

编程入门 行业动态 更新时间:2024-10-26 20:21:46
本文介绍了如何检测是否已触摸 SKSpriteNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试检测我的精灵节点是否已被触摸,但我不知道从哪里开始.

I am trying to detect if my sprite node has been touched and I have no idea where to start.

let Pineapple = SKSpriteNode(imageNamed: "Pineappleimg") Pineapple.userInteractionEnabled = true Pineapple.position = CGPoint(x: CGRectGetMidX(self.frame) - 200, y: CGRectGetMidY(self.frame)); self.addChild(Pineapple)

推荐答案

首先将SKSpriteNode的name属性设置为字符串.

First set the name property of the SKSpriteNode to a string.

pineapple.name = "pineapple" pineapple.userInteractionEnabled = false

然后在Scene中的touchesBegan函数

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch:UITouch = touches.anyObject()! as UITouch let positionInScene = touch.locationInNode(self) let touchedNode = self.nodeAtPoint(positionInScene) if let name = touchedNode.name { if name == "pineapple" { print("Touched") } } }

这是一种方法.您还可以继承 SKSpriteNode 并覆盖其中的 touchesBegan.

This is one way to do it. You can also subclass SKSpriteNode and override the touchesBegan inside it.

class TouchableSpriteNode : SKSpriteNode { override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { print("touched") } }

那就做吧

let pineapple = TouchableSpriteNode(imageNamed: "Pineappleimg") pineapple.userInteractionEnabled = true pineapple.position = CGPoint(x: CGRectGetMidX(self.frame) - 200, y: CGRectGetMidY(self.frame)); self.addChild(pineapple)

更多推荐

如何检测是否已触摸 SKSpriteNode

本文发布于:2023-10-24 17:30:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:SKSpriteNode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!