Unity ray (Ray) and LineRenderer plug-in, the display and disappearance of ray lines

show ray

1. The component LineRenderer must be added

2. Get the LineRenderer component in the code, otherwise an error will be reported

3. The starting point and end point of the ray need to be clear, otherwise there will be big problems with the position of the ray display. For example, in shooting games, the starting position should be at the muzzle of the gun. You only need to give an empty object at the muzzle. To go over it, just put the starting position of the ray on the empty object. Regarding the direction issue, you can determine it according to your own needs. Generally, it is in the z-axis direction of the world coordinates, which is the forward position.

4. Note: Be sure to clarify the three-dimensional coordinates of the empty object, and the empty object itself will change the orientation of the empty object due to certain animations. Otherwise, the position of the ray may be greatly deviated, causing the ray to shift.

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;

public class Players : MonoBehaviour
{
    private LineRenderer line;//线的定义
    public Transform buttle; //射线的起点位置(空物体的位置)
    
    void Start()
    {
         
    line = GetComponent<LineRenderer>();//添加组件
    }

    void Update()
    {
        Fire();
    }
     void Fire()//玩家开火
    {
        if (Input.GetButtonDown(0))
        {
            
           //射线的定义 Ray(射线的开始位置,射线的方向)
            Ray ray = new Ray(buttle.position, transform.forward);

            RaycastHit hit;//被击中位置的点位定义

            line.SetPosition(0, buttle.position);//线的开始位置

            bool b = Physics.Raycast(ray, out hit);//判定射线是否击中目标
            if (b==true)
            {
                line.SetPosition(1, hit.point);//线的最终位置,hit.point被击中的位置

                line.enabled = true; //射线的显示
                //line.enabled = false;//射线的消失      
        
                if (hit.collider.CompareTag("Enemy"))//被击中的目标Tag值
                {
                    Destroy(hit.collider.gameObject,0.1f);//销毁被击中的对象
                       
                }                
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_71624363/article/details/129150189