[SceneKit專題]5-3D空間的觸摸事件

說明

本系列文章是對<3D Apple Games by Tutorials>一書的學習記錄和體會node

此書對應的代碼地址git

SceneKit系列文章目錄github

在平時開發中經常使用的touchesBegan方法在3D中仍然可用. 只不過在3D空間內採用了射線檢測方法來返回觸摸到的物體.swift

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)
}
}
複製代碼
相關文章
相關標籤/搜索