Unity 3D,即使 Sprite 不可见,如何检测鼠标是否位于 2D Sprite 上

问题描述 投票:0回答:2

我使用 Unity3D 游戏引擎,偶然发现了这个问题。 当我尝试检查鼠标是否位于精灵上方时,我可以使用此回调来执行此操作。

private void OnMouseOver()
{
    // Do Something
}

但是如果鼠标不是直接位于精灵上方,则此方法不起作用。 还有其他选择吗?

橙色精灵是我想要检测的精灵,但是蓝色圆圈使它无法检测到鼠标(这看起来不太好,我不是艺术家,但我希望我应该把事情说清楚)

c# unity-game-engine sprite mouse
2个回答
3
投票

如果您想知道鼠标单击下方有哪些对象,请使用以下命令:

示例 - 将其放入您的更新中:

if (Input.GetMouseButtonDown(0))
{
    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var hits = Physics2D.GetRayIntersectionAll(ray, 1500f);

    foreach (var hit in hits)
    {
        print($"Mouse is over {hit.collider.name}");
    }
}

出于性能原因,您可能需要使用:


0
投票

也许你可以使用函数“OnMouseExit();” 以下是 Unity 的官方文章:https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseExit.html

© www.soinside.com 2019 - 2024. All rights reserved.