Unity ray detection collision

Foreword:

Use ordinary collision detection, the detection is not continuous, it is discrete detection every 0.02 seconds, so when the speed of the detected object is relatively fast, it will be directly passed through the object. At this time, you need to use The radiography is checked.

In order to achieve collision detection under high-speed conditions, continuous rays are used to complete such a function.

One, create a ray

Use new Ray to create new Ray (launch position, launch direction multiplied by launch speed)

Ray ray = new Ray(transform.position, transform.forward * 100);  

Two, collision detection

Use Physics.Raycast (ray, out collision object, maximum detection distance) (return bool type) ray detection collision, and will return information about the collided object

 	RaycastHit hitInfo;                                 //定义一个RaycastHit变量用来保存被撞物体的信息;
	 if (Physics.Raycast(ray, out hitInfo, 100))         //如果碰撞到了物体,hitInfo里面就包含该物体的相关信息;
	  {
    
    
	      hitInfo.point;         // 碰撞点的位置; 
	      hitInfo.normal;       //与碰撞点所在平面垂直的向量;
	      hitInfo.collider.gameobject;  //可以得到该物体上的所有信息了;
	  }

Guess you like

Origin blog.csdn.net/xinzhilinger/article/details/108454904