【问题标题】:unity c# touch coordinatesunity c# 触摸坐标
【发布时间】:2016-12-25 02:10:18
【问题描述】:

您好,我正在开发一个简单的游戏项目,我想从我在屏幕上触摸的位置实例化一个游戏对象,我编写了以下代码,但坐标不匹配。它实例化了对象,但我看不到它在屏幕上的位置我想我想解决这个问题,我不知道代码是如何的:

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

        }

【问题讨论】:

    标签: touch coordinates unity5


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多