Swift

对于场景内对象元件的点击响应,我们可以在场景的touchesBegan()方法中内统一处理。

SKScene中touchesBegan()是响应屏幕点击的方法,在这里面我们可以先获取点击位置下所有的对象,然后筛选出需要的对象再调用该对象的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import SpriteKit
 
class GameScene: SKScene {
     
    //当切换到这个场景视图后
    override func didMoveToView(view: SKView) {
 
    }
     
    //响应屏幕点击的方法
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {       
        for touch:AnyObject in touches{
            //获取点击的坐标
            let location = touch.locationInNode(self)
            //该坐标下所有的对象
            var arrObject = self.nodesAtPoint(location)
            //找出为HanggePoint类型的对象
            for p in arrObject {
                let point = p as? HanggePoint
                //如果该对象不为nil,就调用该对象方法
                if point != nil {
                    point.onTouch()
                }
            }           
        }
    }
}
原文地址:https://www.cnblogs.com/Free-Thinker/p/4841097.html