介绍
unity,怎么利用line renderer发射光线?
方法
给物体挂载Line renderer组件,默认禁用
给物体挂载Light组件,默认禁用
给物体挂载粒子系统组件,不播放
挂载简单脚本
using UnityEngine;
using System.Collections;
public class PlayerShooting : MonoBehaviour
{
LineRenderer gunLine; // 射线显示效果组件
Ray gunRay; // 射出的射线
public LayerMask layerMask; // 用于射线检测的层级掩码
void Start()
{
gunLine = GetComponent<LineRenderer>();
}
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
gunLine.enabled = true; // 启动射线显示效果
gunRay.origin = transform.position; // 设置射出的射线的起点为玩家位置
gunRay.direction = transform.TransformDirection(Vector3.forward); // 设置射出的射线的方向为玩家正前方
gunLine.SetPosition(0, transform.position); // 设置射线的起点为玩家位置
if (Physics.Raycast(gunRay, out RaycastHit hit, 100f, layerMask)) // 检测是否击中物体
{
gunLine.SetPosition(1, hit.point); // 设置射线的结束点为击中的点
}
else
{
gunLine.SetPosition(1, transform.position + gunRay.direction * 100f); // 设置射线的结束点为射线的最大范围
}
Invoke("DisableLineRenderer", 0.1f); // 延迟禁用射线显示效果
}
void DisableLineRenderer()
{
gunLine.enabled = false; // 禁用射线显示效果
}
}
这段代码实现了基于鼠标输入的玩家射击功能,并在射击时显示射线显示效果,根据射出的射线检测是否击中物体,并在击中时显示射线的结束点为击中的点,未击中时显示射线的结束点为射线的最大范围,同时还加入了延迟禁用射线显示效果的功能,避免射线显示效果持续显示。
加入其他特效完整代码
using UnityEngine;
using System.Collections;
public class PlayerShooting : MonoBehaviour
{
Light gunLight; // 枪口火光效果组件
LineRenderer gunLine; // 射线显示效果组件
Ray gunRay; // 射出的射线
public LayerMask layerMask; // 用于射线检测的层级掩码
ParticleSystem gunParticies; // 射击时的粒子效果组件
float timer; // 计时器,用于控制枪光和射线的显示时间
void Start()
{
gunLight = GetComponent<Light>();
gunLine = GetComponent<LineRenderer>();
gunParticies = GetComponent<ParticleSystem>();
}
void Update()
{
timer += Time.deltaTime;
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
if (timer > 0.1f)
{
timer = 0;
gunLine.enabled = false;
gunLight.enabled = false;
}
}
void Shoot()
{
gunLight.enabled = true; // 启动枪口火光效果
gunLine.enabled = true; // 启动射线显示效果
gunRay.origin = transform.position; // 设置射出的射线的起点为玩家位置
gunRay.direction = transform.TransformDirection(Vector3.forward); // 设置射出的射线的方向为玩家正前方
gunLine.SetPosition(0, transform.position); // 设置射线的起点为玩家位置
gunParticies.Stop();
gunParticies.Play(); // 播放射击时的粒子效果
if (Physics.Raycast(gunRay, out RaycastHit hit, 100f, layerMask)) // 检测是否击中物体
{
gunLine.SetPosition(1, hit.point); // 设置射线的结束点为击中的点
}
else
{
gunLine.SetPosition(1, transform.position + gunRay.direction * 100f); // 设置射线的结束点为射线的最大范围
}
}
}