通过射线进行射击,线段渲染器、灯光和粒子系统完成粒子特效;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShoot : MonoBehaviour
{
private float timeBt=0.35f;//两次发射的时间间隔
private float range=100f;//射线的长度
private Ray shootRay;//射线
private RaycastHit shootHit;//射线检测
private float timerShoot;//计时器
private ParticleSystem gunPa;//粒子效果
private LineRenderer gunLine;//线段渲染器
private Light gunLight;//灯光
private float effTime=0.2f;//粒子效果显示的时间长度
private int shootMask;
// Start is called before the first frame update
void Start()
{
timerShoot = 0;
gunPa = GetComponent<ParticleSystem>();//获取组件
gunLight = GetComponent<Light>();
gunLine = GetComponent<LineRenderer>();
shootMask = LayerMask.GetMask("ShootMask");//获取层级
}
// Update is called once per frame
void Update()
{
timerShoot += Time.deltaTime;//计时器
Shoot();
}
//射击
public void Shoot()
{
if(Input.GetMouseButton(0)&&timerShoot>=timeBt)
{
timerShoot = 0;
//激活组件
gunLine.enabled = true;
gunLight.enabled = true;
//先关闭粒子效果在打开粒子效果
gunPa.Stop();
gunPa.Play();
gunLine.SetPosition(0, transform.position);//线段的起始位置
shootRay.origin = transform.position;//射线的起始位置(源头)需与线段相同
shootRay.direction = transform.forward;//Z轴,蓝色轴的正方向
//如果射线检测到
if(Physics.Raycast(shootRay,out shootHit,range,shootMask))
{
gunLine.SetPosition(1, shootHit.point);//线段的终点在射线检测点处
}
else
{
gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);//线段终点
}
}
//关闭特效
if(timerShoot>effTime)
{
gunLine.enabled = false;
gunLight.enabled = false;
}
}
}