检测游戏对象上的触摸

时间:2020-05-14 11:05:51

标签: c# unity3d

我想在没有成功的情况下检测对GameObject的触摸。我从一些示例中复制的代码是:

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Debug.Log("Mouse Clicked!!");
        Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 worldPoint2D = new Vector2(worldPoint.x, worldPoint.y);
        RaycastHit2D hit = Physics2D.Raycast(worldPoint2D, Vector2.zero);
        Debug.Log(hit.collider);

    }
}

输出始终为null:(

游戏对象没有移动,它是带有盒子大肠菌的简单立方体。

2 个答案:

答案 0 :(得分:0)

尝试将Vector3 worldPoint切换为Vector2。像这样:

Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 worldPoint2D = new Vector2(worldPoint.x, worldPoint.y);

,然后在光线投射中使用worldPoint2D

答案 1 :(得分:0)

正在回答自己...我无法使用Phisycs2D.Raycast方法解决问题,但是Phisics.Raycast可以完成工作:

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 100))
        {
            Debug.Log(hit.collider);
        }
    }
}