插件的使用
本次开发没有使用插件
坦克移动功能
public float fSpeed = 5; //坦克行进速度
public float aSpeed = 3; //坦克旋转速度
public int playerSymbol = 1; //玩家标识,用于区分坦克
public Rigidbody rb; //刚体组件
public AudioSource auds; //音频控制器
public AudioClip idleAudio; //坦克空转时引擎音效
public AudioClip moveAudio; //坦克移动时引擎音效
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody>(); //初始化刚体组件
auds = this.GetComponent<AudioSource>(); //初始化音频组件
}
// Update is called once per frame
void Update()
{
Moving();
}
void Moving() //坦克行动代码
{
float v = Input.GetAxis("VerticalPlayer" + playerSymbol); //通过玩家标识绑定不同的虚拟轴
rb.velocity = transform.forward * v * fSpeed; //设置行进速度
float h = Input.GetAxis("HorizontalPlayer" + playerSymbol);//通过玩家标识绑定不同的虚拟轴
rb.angularVelocity = transform.up * h * aSpeed; //设置旋转速度
if (Mathf.Abs(h) > 0 || Mathf.Abs(v) > 0) //当坦克不为空转时
{
auds.clip = moveAudio; //音频控制播放引擎移动音效
if (auds.isPlaying == false) //防止音频不断重复播放卡死
{
auds.Play();
}
}
else //坦克空转时
{
auds.clip = idleAudio; //播放空转音效
if (auds.isPlaying == false) //防止卡死
{
auds.Play();
}
}
}
虚拟轴的绑定
两套轴,分别为Player1和Player2
Player1的水平(旋转)移动轴为a和d
Player1的垂直(行进)移动轴为w和s
Player2的水平(旋转)移动轴为←和→
Player2的垂直(行进)移动轴为↑和↓
下图以Player1的水平(旋转)移动轴的设定为例,不再赘述其他图片。
坦克开火功能
private Transform shellPosition; //子弹初始生成位置
public GameObject shellPrefab; //子弹预制体
public float shellSpeed = 10; //子弹飞行速度
public KeyCode fireKey = KeyCode.Space; //开火按键绑定
public AudioClip fireAudio; //子弹发射音效
// Start is called before the first frame update
void Start()
{
shellPosition = transform.Find("ShellPosition"); //初始化子弹生成位置,在unity中优先摆放好了位置
}
// Update is called once per frame
void Update()
{
fire();
}
void fire()
{
if(Input.GetKeyDown(fireKey)) //当按下开火按钮
{
AudioSource.PlayClipAtPoint(fireAudio, transform.position); //生成开火音效
GameObject g = GameObject.Instantiate(shellPrefab, shellPosition.position, shellPosition.rotation); //实例化子弹预制体
g.GetComponent<Rigidbody>().velocity = g.transform.forward * shellSpeed; //将实例化的子弹绑定刚体,以获得发射速度
}
}
坦克血量功能
给坦克增加一个明显的血量条,根据当前生命值的比例而改变
private int hpMax = 100; //坦克最大生命值
public int hp = 100; //坦克当前生命值
public GameObject tankExpPrefab; //坦克爆炸动画
public AudioClip tankExpAudio; //坦克爆炸音效
public Slider hpSlider; //坦克血量显示条
public GameObject Canvas; //血量显示条画布
void injury()
{
hp = hp - 10;
hpSlider.value = (float)hp / hpMax; //计算当前血量占比,显示在血量条上
if (hp <= 0)
{
GameObject.Instantiate(tankExpPrefab, transform.position, transform.rotation);//生成爆炸动画
GameObject.Destroy(this.gameObject); //摧毁坦克实体
AudioSource.PlayClipAtPoint(tankExpAudio, transform.position); //播放坦克爆炸音效
Canvas.SetActive(true); //将游戏结束的UI激活显示
}
}