Ray Ray

Today I want to summarize the Unity about ray related things, if there is some misunderstanding also hope to correct, thank you!

1. What Ray rays

First, we need to know the two components of a ray: origin and direction, so we need these parameters to instantiate a ray.

Ray instantiation:

Ray (Vector3 Origin,Vector3 direction) = new (Vector3 origin,Vector3 direction);

The first parameter origin indicates the starting point of the ray, and the second parameter direction indicates the direction of the ray.specialCamera.main.ScreenPointToRay(Vector3 targetPosition)Where targetPosition usually uses the screen coordinates input. mousePosition, which indicates that the camera emits rays to the mousePosition.

2. Introduction of RaycastHit class

Function: Used to store collision information generated by emission rays. Common member variables are:

Point: Coordinates of the intersection of ray and collider

Collider: The object that collides with a ray

Distance: Coordinates of the ray starting point to the point of intersection with the colliding object

3. Ray debugging (display)

Debug.DrawRay(Vector3 start, Vector3 dir, Color color, float duration)

Dir: direction of the ray color: color of the ray during debugging duration: duration of the ray during debugging

The debug. DrawRay function has a lot of overloading. For example, we can not write “Color”, “Color”, “float duration”, then when we are in edit mode, the ray Color is white by default, and the lifetime is one frame by default.

Place the script below on an object, run it, and in edit mode you will see a red ray starting at (0,0,0) in the positive X-axis direction.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shoot : MonoBehaviour
{
  
    void Update()
    {
        Vector3 origin = new Vector3(0.0.0);
        Vector3 direction = new Vector3(1f.0.0);
        Ray ray = new Ray(origin, direction);
        Debug.DrawRay(ray.origin, ray.direction * 100f, Color.red, 1f); }}Copy the code

4. Ray emission: Bool Physics.Raycast(Ray Ray, Out RaycastHit hitInfo, float maxDistance, int layerMask, QueryTriggerInteraction);Parameter start: the starting point of the ray

Parameter ray: ray

Parameter hitInfo: Stores information about objects hit by rays

Parameter maxDistance: The maximum distance of the ray

Parameter layerMask: Ray detection layer, with int decimal conversion to binary judgment, (decimal)2->(binary)10, indicating the first layer of inspection TransparentFX;

Parameter QueryTriggerInteraction: query whether Ignore is the Trigger (Trigger), Ignore use QueryTriggerInteraction. Ignore, detection using QueryTriggerInteraction. Collide

If this ray touches another object with a collider on the specified layer, store the object information in hitInfo and return true. If it does not touch the object, return false.

Of course, this function has other overloads. For example, we can not write float maxDistance, int layerMask, QueryTriggerInteraction, so the maximum distance emitted is infinite by default, Layer 2 layer in addition to the default examination Ignore Raycast outside of the other layers, parameters for QueryTriggerInteraction QueryTriggerInteraction. UseGlobal, is set up inside the default Settings for our project. If checked, default detection, otherwise ignored;

We then add the following script to an object and place a box collider in the path of the ray. Then run and click the left mouse button, and you’ll find the type of collider the ray hit on the console.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rayshoot : MonoBehaviour
{
    bool isnoShoot;
   public Vector3 Direction;
   

    // Update is called once per frame
    void Update()
    {
        // Input.getMouseButtonDown (0) Click the left mouse button to return true, otherwise return false
        isnoShoot = Input.GetMouseButtonDown(0);
        // Shoot();
        if (isnoShoot)
        {
            Vector3 origin = new Vector3(0.0.0);
            Vector3 direction = new Vector3(1f.0.0);
            Ray ray = new Ray(origin, direction);
            // an example of a ray starting at (0,0,0) with a positive direction along the X axis
            Debug.DrawRay(ray.origin, ray.direction * 100f, Color.red, 1f);
            RaycastHit hit;
            Physics.Raycast(ray, out hit, 100f.1, QueryTriggerInteraction.Collide); Debug.Log(hit.collider); }}}Copy the code

Application scenario of ray

There are a lot of scenarios for ray-shooting, but due to space constraints, we will simulate the character shooting.

First we need to create a spherical collider in the scene, then drag it to the preform, then delete the spherical collider in the scene, and then add the following script to the preform.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet : MonoBehaviour
{
    Vector3 shootdirection;
    float speed;
    // Start is called before the first frame update
    void Start()
    {
        speed = 6f;
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(shootdirection*speed*Time.deltaTime,Space.World);
    }

    /// <summary>
    ///Initializes the direction of bullet movement
    /// </summary>
    /// <param name="shoot"></param>
   public void startState(Ray shoot){ shootdirection = shoot.direction; }}Copy the code

Then we created a spherical collider to simulate the character in the scene and added the following script to it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class roleshoot : MonoBehaviour
{
    bool isnoShoot;
    public bullet bullets;
 
    // Update is called once per frame
    void Update()
    {
        isnoShoot = Input.GetMouseButtonDown(0);
        if(isnoShoot) { RoleShoot(); }}void RoleShoot()
    {
        // The camera emits rays where the mouse is
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;// Define a RaycastHit that accepts information about the object being hit
        
        // Emit rays
       Physics.Raycast(ray, out hit, 100f.1, QueryTriggerInteraction.Collide);
     
       
        Vector3 shootdirection = hit.point - transform.position;

        // The ray that the main character should emit
        Ray roleray = new Ray(transform.position, shootdirection);

        // Make ray visible in edit mode
        Debug.DrawRay(roleray.origin, roleray.direction*1000f, Color.red, 2f);
        // Generate bullets,
        bullet bullet = Instantiate(bullets, transform.position, bullets.gameObject.transform.rotation);
        // Initialize bullet orientationbullet.startState(roleray); }}Copy the code

Then add the preform manually.Then click on the ground to fire the bullet.