【问题标题】:Only select the first sprite in a pile of sprites (Unity3D 2D-game)只选择一堆精灵中的第一个精灵(Unity3D 2D-game)
【发布时间】:2014-07-05 02:43:32
【问题描述】:

我在游戏板上有许多相互重叠的精灵。当我使用鼠标并选择顶部的精灵时,鼠标位置下的所有精灵都被选中。我的问题是如何只选择我点击的精灵而不捕捉下面的精灵?

这是我用于测试的代码,附在精灵上:

function Update () {
if(Input.GetMouseButtonDown(0)) {

    var theActualMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

//      print("ALL MousePosition: " + theActualMousePosition);

    if(collider2D.OverlapPoint(theActualMousePosition)) {

//          print("HIT theActualMousePosition: " + theActualMousePosition);

    print(collider2D.gameObject.tag);

    } 
}
}

【问题讨论】:

    标签: unity3d unityscript


    【解决方案1】:

    您得到的结果完全符合预期,因为您的代码放置在 GameObjects 上,您应该做的是将脚本从这些对象中推出或使用 OverlapPoint 以外的其他函数(因为重叠点不会简单地检查碰撞检查您是否在对象的范围内,这意味着它对所有对象都有效)

    一些想法:

    • 使用 OnMouseDown 应该只为遇到的第一个对撞机提供一个事件
    • 使用来自相机的光线投射:Camera.ScreenPointToRay 应该能够用于光线投射,然后只检查遇到的第一个对撞机
    • 根据layer collision Order使用Layers。

    编辑:

    或者你也可以反过来投射光线:

    function Update () {
        if(Input.GetMouseButtonDown(0)) {
    
            var theActualMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    
            Vector3 direction = (transform.Position-theActualMousePosition).normalized;
            Ray ray = Ray(transform.Position,direction)
    
            if(Physics.Raycast(ray) == null) {
    
                //Then there is nothing between the object and the camera then the object is the first one
                print(collider2D.gameObject.tag);
    
            } 
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多