ShootGame1(主角的射击)

该博客介绍了在Unity中创建主角射击功能的实现过程,包括使用射线检测、线段渲染器、粒子系统和灯光来模拟射击效果。通过Input.GetMouseButton(0)判断点击并控制发射间隔、粒子效果显示时间以及射线的起点和终点设置,从而实现游戏内的射击交互。
摘要由CSDN通过智能技术生成

通过射线进行射击,线段渲染器、灯光和粒子系统完成粒子特效;

   

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;
        }
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值