2016-12-25 138 views
-1

嗨我正在一個簡單的遊戲項目,我想實例化一個gameobject從我觸摸屏幕的位置我寫了下面的代碼,但座標不匹配。它實例化對象,但我不能看到它出現在屏幕上,我認爲有件事我錯過了解決這個問題,我不知道是怎麼這裏的代碼:統一c#觸摸座標

if (Input.GetTouch(0).phase == TouchPhase.Began) 
     { 

      Debug.Log("touch begun" + Input.GetTouch(0).position); 
      Vector3 touchDeltaPosition = Input.GetTouch(0).position; 
      Instantiate(bulletPrefab, Input.GetTouch(0).position, Quaternion.identity); 

     } 

回答

0

Input.GetTouch的值(0 ).position是屏幕的像素座標。 對象的實例化處於世界空間座標中。 您應該獲得世界空間中的屏幕角點座標,並使用觸摸值從那裏偏移x和y。

嘗試了這一點:

 if (Input.GetTouch(0).phase == TouchPhase.Began) 
     { 
      Vector3 touchData = Input.GetTouch(0).position; 

      touchData.x = x; 
      touchData.y = y; 
      // Construct a ray from the current touch coordinates 
      Ray ray = Camera.main.ScreenPointToRay(new Vector2(touchData.x, touchData.y)); 
      if (Physics.Raycast(ray)) 
      { 
       float desiredValueForZ = 2f; //this depends on your project stuff, I don't know. 
       Instantiate(bulletPrefab, Camera.main.ScreenToWorldPoint(new Vector3(touchData.x, touchData.y, desiredValueForZ)), transform.rotation); 
      } 
     }