This is the 23rd day of my participation in the August More Text Challenge

concept

A ray is an endless line of light emitted from a point in the 3D world in one direction that will stop when it colliders with other objects in its trajectory.

Application: ray is widely used in collision detection (such as whether the bullet hits the target or not), role movement and so on.

Some structures (classes) related to Ray:

  • Physics: RayCast() emits a ray;
  • Ray: Object representing the Ray itself
  • RaycastHit (Structure) : Collision information for ray and other colliders

Plotting ray function

  1. Draw a blue ray of z-axis forward length 10 from this object:

Debug.DrawLine(transform.position, Vector3.forward * 10,Color.blue);

  1. Draws a red ray of length 10 in the negative X-axis direction from this object

Debug.DrawRay(transform.position, Vector3.left * 10,Color.red);

Parameter Description:

  1. The first parameter is the drawn position
  2. The second argument is the drawn point, which defaults to 1 and can be multiplied by a value of type float to increase its ray length
  3. The third parameter is color
  4. The fourth parameter is the ray region. If you change the direction of the ray, the ray will form a region of type float. The larger the value, the longer it will stay.

Ray detection

Related parameter concepts of radiographic detection:

  1. RaycastHit hit: Raycast collision (this variable is used to store information about which objects this ray hits)

  2. Camera. The main. ScreenPointToRay (position) : screen location shooting line: return a ray from the Camera through a screen

PS:

  • The resulting rays are in world space, starting from the near clipping plane of the camera and passing through the screen position(x,y) pixel coordinates (Position. z is ignored.
  • Screen space is defined in pixels. The bottom left of the screen is (0,0); The top right is (pixelWidth,pixelHeight).

The API:

  1. Ray Camera. Main. ScreenPointToRay Vector3 (pos) returns a Ray Ray from the Camera to the screen to specify a point
  2. Ray Ray class
  3. RaycastHit ray projection collision information
  4. Bool Physics.Raycast Note: If a ray is cast from the inside of a sphere to the outside, return false.

Five parameters of a ray

RaycastHit[] RaycastAll(Ray ray, float distance, int layerMask)

Parameters: -origin: the starting point of the ray in world coordinates -direction: the direction of the ray -distance: the length of the ray -hit: pass an empty collision information class using the out keyword in c#, and then assign the value after the collision. Can get collision object transform, rigidbody, point information, etc. – layerMask: Only colliders in the layerMask layer are selected. Colliders in other layers are ignored. Selective collision filters objects.