Study Notes for beginners, please correct me if you have any mistakes. The number is also please point out, thank you.
Ray (Ray) is a technique used in all 3D games and is widely used in path finding, Ai logic, and hit judgment.
Create a sphere as a player, create a cube as a barrier, the new script binds to the player, the code is as follows:
usingUnityengine;usingSystem.Collections; Public classC_7_5:monobehaviour {PrivateVector3 Direction =NewVector3 (1,0,0);//forward and Ray direction Private floatDistance = 1f;//Ray Distance voidUpdate () {transform.position+ = direction * TIME.DELTATIME;//player Move RightRay Ray =NewRay (transform.position, direction);//New RayRaycasthit info;//variables that receive the ray impact information//emission Ray Method 1 if(Physics.raycast (Ray, outinfo,distance)) { //Discover obstaclesDebug.Log ("there are obstacles ahead ."+info.collider.name); } debug.drawline (Ray.origin,ray.origin+ direction*distance);//show Ray with DrawLine// //emission Ray Method 2//if (Physics.raycast (transform.position, New Vector3 (1,0,0), 1)) {//Debug.Log ("Obstacles ahead!");// }// //emission Ray Method 3//if (Physics.raycast (transform.position,transform.forward,1)) {//Debug.Log ("Obstacles ahead!");// } }}
First create the Vector3 variable direction, which represents the forward and radial direction
Then create the float type cold distance represents the distance of the ray termination
The Player object is the sphere moving right forward
Then create a Ray object, the first parameter of the constructor is the beginning of the Ray, and the second parameter is the direction of the Ray
Raycasthit Info Variables for Ray impact information
Raycast returns a Boolean value, True indicates collision to something, false means no
As for what object the ray collides with, where to return to the second parameter info
Finally, the ray visualization is displayed using the Debug.drawline () function.
Note that the function needs to tick the gizmos option of the game window to display
You can also not create ray, such as Physics.raycast (transform.position,transform.forward,1), to directly pass in the element, start, and direction of the Ray
Physics engine--05 Ray