[SceneKit专题]5-3D空间的触摸事件

1,660 阅读1分钟

说明

本系列文章是对<3D Apple Games by Tutorials>一书的学习记录和体会

此书对应的代码地址

SceneKit系列文章目录

在平时开发中常用的touchesBegan方法在3D中仍然可用. 只不过在3D空间内采用了射线检测方法来返回触摸到的物体.

QQ20170404-104513@2x.png
当有触摸事件发生时:

  1. 拿到用户触摸在屏幕上的位置.
  2. 转换到SCNView的坐标系中.
  3. 当触摸点在SCNView上时,发射一个射线,返回与该射线相交的一系列物体.
override func touchesBegan(touches: Set<UITouch>, withEvent event:
UIEvent?) {
// 1 拿到触摸对象
  let touch = touches.first!
  // 2 转换坐标系
  let location = touch.locationInView(scnView)
  // 3 执行hitTest,发射射线,返回相交的物体
  let hitResults = scnView.hitTest(location, options: nil)
  // 4 
  if hitResults.count > 0 {
// 5 取出最近的物体
    let result = hitResults.first!
    // 6 处理该节点
    handleTouchFor(result.node)
}
}