Ray
Ray, the analogy is the bullets in the game. A point in the 3D world is a line without an end point. During the launch process, the launch will stop once it is in conflict with other objects.
Principle of radiation
When creating a Ray, you first need to know the coordinates of the ray's start point and end point in the 3D world.
Using unityengine; using system. collections; public class script_06_08: monobehaviour {void Update () {// create a ray, which is emitted from zero point to the object Ray = new ray (vector3.zero, transform. position); // calculates the start and end points of the ray. raycasthit hit; physics. raycast (Ray, out hit, 100); // use the debugging method to draw this line (the debugging method records that exist in the scene view) debug. drawline (Ray. origin, hit. point );}}
After running:
In the above Code, the Debug. drawline () method can only be seen in the scene view. To draw rays in the game, you need to use the GL graphics library or linerenderer method.
Collision monitoring
Rays can be used to determine the collision with other objects in the game. In this example, a ray is sent to the point where the mouse moves at the camera position. It is like shooting a shot at the target to determine whether to hit the target.
Using unityengine; using system. collections; public class script_06_09: monobehaviour {// target texture public texture; // message private string Info; void Update () {// create a Ray from the camera position to the mouse position = camera. main. screenpointtoray (input. mouseposition); raycasthit hit; // determines whether the ray hits the game object if (physics. raycast (Ray, out hit) {info = "hit target";} else {info = "not hit target" ;}} void ongui () {// calculate the coordinate rect = new rect (input. mouseposition. x-(texture. width> 1), screen. height-input. mouseposition. y-(texture. height> 1), texture. width, texture. height); // draw a quasi-Central texture GUI. drawtexture (rect, texture); // enter the target information guilayout. label (Info + ", with the coordinates:" + input. mouseposition );}}
After running:
The above Code uses camera. main. the screenpointtoray method is used to wear a ray emitted by the camera to the current position of the mouse, and then physics is used. raycast checks whether this Ray is in line with a game. If yes, true is returned. If no, false is returned.
[unity 3D] Study Notes 40: rays