【问题标题】:How to find which side of a collider has been hit from hit.normal?如何从hit.normal中找到对撞机的哪一侧?
【发布时间】:2011-09-16 15:47:26
【问题描述】:

在 Unity3d 中,我可以使用 hit.normal 获取对撞机碰撞的表面的法线,但是有没有办法找到哪一面被击中了 Unity3d 提供的东西?

一种解决方案是查看法线的方向,对于静态对象应该很好,但是对于方向发生变化的动态和移动对象呢?

【问题讨论】:

    标签: collision-detection unity3d game-physics


    【解决方案1】:
    function OnCollisionEnter(collision : Collision)
    {
        var relativePosition = transform.InverseTransformPoint(collision.contacts);
    
        if(relativePosition.x > 0) 
        {
            print(“The object is to the right”);
        } 
        else 
        {
            print(“The object is to the left”);
        }
    
        if(relativePosition.y > 0) 
        {
            print(“The object is above.”);
        } 
        else 
        {
            print(“The object is below.”);
        }
    
        if(relativePosition.z > 0) 
        {
            print(“The object is in front.”);
        } 
        else 
        {
            print(“The object is behind.”);
        }
    }
    

    【讨论】:

    【解决方案2】:
    void OnCollisionEnter(Collision collision)
    {            
        Vector3 dir = (collision.gameObject.transform.position - gameObject.transform.position).normalized;
    
        if(Mathf.Abs(dir.z) < 0.05f)
        {
            if (dir.x > 0)
            {
                print ("RIGHT");    
            }
            else if (dir.x < 0)
            {
                print ("LEFT");             
            }
        }
        else
        {
            if(dir.z > 0)
            {
                print ("FRONT");
            }
            else if(dir.z < 0)
            {
                print ("BACK");
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      这行得通:

      function OnCollisionEnter(collision: Collision) {
          var relativePosition = transform.InverseTransformPoint(collision.transform.position);
      
          if (relativePosition.x > 0) 
          {
              print ("The object is to the right");
          }
          else 
          {
              print ("The object is to the left");
          }
      
          if (relativePosition.y > 0) 
          {
              print ("The object is above.");
          } 
          else 
          {
              print ("The object is below.");
          }
      
          if (relativePosition.z > 0) {
              print ("The object is in front.");
          }
          else 
          {
              print ("The object is behind.");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2023-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-27
        • 2020-11-11
        • 1970-01-01
        • 2013-04-21
        • 1970-01-01
        相关资源
        最近更新 更多