1.设置第一人称,把摄像机添加到物体身上改名为"Head"。
2.让人物移动,添加代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class yidong : MonoBehaviour
{
private Transform head;
private Transform body;
// Start is called before the first frame update
void Start()
{
head = transform;
body = transform.parent;
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
float mousex = Input.GetAxis("Mouse X");
if (mousex != 0)
{
body.Rotate(Vector3.up, mousex * 380 * Time.deltaTime);
}
float mousey = Input.GetAxis("Mouse Y");
if (mousey != 0)
{
head.Rotate(Vector3.left, mousey * 100 * Time.deltaTime);
}
if (Vector3.Angle(body.forward, head.forward) > 60)
{
head.Rotate(Vector3.left, mousey * -100 * Time.deltaTime);
}
if (Input.GetKey(KeyCode.W))
{
body.Translate(Vector3.forward * 5.0f * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
body.Translate(Vector3.back * 5.0f * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
body.Translate(Vector3.left * 5.0f * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
body.Translate(Vector3.right * 5.0f * Time.deltaTime);
}
}
}
3.为枪添加代码,使其能射击,主要是用于控制枪械的开火和换弹功能。它通过检测用户输入、计时器和动画事件来实现这些功能。:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class guncontral : MonoBehaviour
{
//枪口火焰生成位置
public Transform firepoint;
//枪口火焰物体
public GameObject fireper;
//子弹生成位置
public Transform bulletpoint;
//子弹物体
public GameObject bulletper;
//子弹个数
private int bulletCount = 10;
// 开火间隔
private float cd = 0.2f;
//实际开火的时间 计时器
private float timer = 0;
private AudioSource gunvoice;
public AudioClip clip;
public Text bulletcount;
// Start is called before the first frame update
void Start()
{
gunvoice = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
//计算实际开火间隔
timer = timer + Time.deltaTime;
if (Input.GetMouseButton(0) && bulletCount > 0 && timer > cd)
{//开枪
timer = 0;
//火焰生成
Instantiate(fireper, firepoint.position, firepoint.rotation);
//子弹生成
Instantiate(bulletper, bulletpoint.position, bulletpoint.rotation);
bulletCount--;//bulletcount=bulletcount-1
gunvoice.PlayOneShot(clip);
bulletcount.text = "子弹数:" + bulletCount;// 100 "100"
}
if (bulletCount == 0)
{
//Invoke("Reload", 2.0f);
GetComponent<Animator>().SetTrigger("Reload");
Reload();
}
if (Input.GetKeyDown(KeyCode.R) && bulletCount != 10)
{
GetComponent<Animator>().SetTrigger("Reload");
Reload();
}
}
void Reload()
{//换弹
bulletCount = 10;
bulletcount.text = "子弹数:" + bulletCount;
}
}