统一c#触摸坐标

问题描述:

嗨我正在一个简单的游戏项目,我想实例化一个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); 

     } 

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); 
      } 
     }