今天实现的内容:
脚本结构的优化
为接下来的切换枪械做铺垫,脚本需要再进行一次大改,目的是再次将枪械的操作用一个脚本统一管理,方便接下来对不同枪械能使用同一套代码进行操作。将之前在AssaultRifle脚本中实现的控制操作放到新脚本中进行,再进行封装以及将一些写在AssaultRifle脚本中的枪械共有的属性再搬到Firearms中。
以下是新脚本WeaponManager ,用来管理所有武器的操作逻辑,以及主副武器的切换。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Scripts.Weapon;
// 用于武器的控制 切换
public class WeaponManager : MonoBehaviour
{
// 主武器
public Firearms mainWeapon;
// 副武器
public Firearms secondaryWeapon;
// 当前手上拿着的武器
private Firearms currentWeapon;
// FPCharacterControllerMovement的引用 用于传递Animator
private FPCharacterControllerMovement controller;
// 切换武器
private void SwapWeapon()
{
if (Input.GetAxis("Mouse ScrollWheel") != 0) //当使用滚轮时
{
currentWeapon.gameObject.SetActive(false); //隐藏现在的武器
currentWeapon = (currentWeapon == mainWeapon) ? secondaryWeapon : mainWeapon; //切换武器
currentWeapon.gameObject.SetActive(true); //显示切换后的武器
controller.SetupAnimator(currentWeapon.gunAnimator); //切换Animator
}
else if (Input.GetKeyDown(KeyCode.Alpha1)) //当按下键盘1键时
{
currentWeapon.gameObject.SetActive(false);
currentWeapon = mainWeapon;
currentWeapon.gameObject.SetActive(true);
controller.SetupAnimator(currentWeapon.gunAnimator);
}
else if (Input.GetKeyDown(KeyCode.Alpha2)) //当按下键盘2键时
{
currentWeapon.gameObject.SetActive(false);
currentWeapon = secondaryWeapon;
currentWeapon.gameObject.SetActive(true);
controller.SetupAnimator(currentWeapon.gunAnimator);
}
}
private void Start()
{
if(currentWeapon == null)
{
Debug.Log("current weapon is null");
}
currentWeapon = mainWeapon;
currentWeapon.gameObject.SetActive(true);
secondaryWeapon.gameObject.SetActive(false);
controller = GetComponent<FPCharacterControllerMovement>();
controller.SetupAnimator(currentWeapon.gunAnimator);
}
private void Update()
{
// 如果当前没有武器 什么都不执行
if (!currentWeapon) return;
// 换弹
if (Input.GetKeyDown(KeyCode.R))
{
currentWeapon.ReloadAmmo();
}
//按住扳机
if (Input.GetMouseButton(0))
{
currentWeapon.HoldTrigger();
}
//松开扳机
if(Input.GetMouseButtonUp(0))
{
currentWeapon.ReleaseTrigger();
}
// 瞄准 按下就会瞄准
if (Input.GetMouseButtonDown(1))
{
currentWeapon.Aiming(true);
}
// 松开按键退出瞄准
if (Input.GetMouseButtonUp(1))
{
currentWeapon.Aiming(false);
}
SwapWeapon();
}
}
优化后的AssaultRifle类,将瞄准放到Firearms中进行实现,同时将isAllowShooting放到AssaultRifle中实现。isAllowShooting我认为除了自动武器的射速控制,还可以用来实现武器半自动,栓动。Shooting也略有不同,判断是否还有子弹被放到了Firearms中实现。
using UnityEngine;
using System.Collections;
using System.