当前位置:网站首页>Unity check whether the two objects have obstacles by ray

Unity check whether the two objects have obstacles by ray

2022-07-05 04:55:00 yoyoHm

Function description :

Ray(Vector3 origin, Vector3 direction )

Ray The starting point of the ray , The direction of the ray (Unity 3D It will automatically normalize units )) 

This overloaded function uses existing rays Ray As parameters and get collision information RaycastHit.

Raycast(Ray ray, RaycastHit hitInfo, float distance = Mathf.Infinity( Infinite ), intlayerMask = DefaultRaycastLayers);

Raycast( ray , Collision information , distance , Ray collision level );
     

The direction of the ray : Find a vector by subtracting two points

  // Save collision information 
    RaycastHit m_hit;
    Ray ray = new Ray(transform.position ,playerTransform.transform.position-transform.position);  
    if(Physics.Raycast(ray, out m_hit,  Vector3.Distance(transform.position, playerTransform.position)))  
    {  
         if (m_hit.transform.tag == "Wall" )
              {
                Debug.Log(" Name of collision object   "+m_hit.transform.name);
                Debug.DrawLine(transform.position ,playerTransform.transform.position,Color.red);
              }
    }

 

 

Add in case of subsequent use :

X-ray penetration testing , Check that multiple rays collide with objects

Physics.RaycastAll: This function is related to Physics.Raycast The difference is that it can detect multiple objects touched by rays . The return value is an array of collision information , Whether or not you touch an object , Arrays are not null , If you don't touch the object, the length of the array will be 0.

Physics.RaycastNonAlloc: This function is related to Physics.RaycastAll similar , It is also used to detect objects touched by rays . The difference lies in the return value ,Physics.RaycastAll The return value is an integer , Is the number of objects hit by rays .
 

原网站

版权声明
本文为[yoyoHm]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140626087889.html