【问题标题】:Detecting touch on gameobject检测游戏对象上的触摸
【发布时间】:2020-05-14 23:59:19
【问题描述】:

我想在没有成功的情况下检测到对 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);

    }
}

输出始终为空:(

游戏对象没有移动,是一个带有盒子碰撞器的简单立方体。

【问题讨论】:

标签: c# unity3d


【解决方案1】:

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

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

然后在光线投射中使用worldPoint2D

【讨论】:

  • 您也可以尝试在raycast函数中添加第三个参数并将其设置为较高的数字。这个参数表示距离,或许会有帮助。
【解决方案2】:

回答自己...我无法使用 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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    相关资源
    最近更新 更多