1.将枪模型放入摄像机内,将枪的位置调整为真实的“手上”,并且把枪设置为摄像机的子对象。
2.制作子弹模型,并将子弹命名为bullet设置为预制体,添加 Sphere Collider 和 Rigidbody。
3.创建bullet射出去消失C#代码,命名为Bullet。
代码内容为:
void Start()
{
GetComponent<Rigidbody>().AddForce(transform.forward * 2000);
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
}
4.将枪口火焰GameObject fireper创建为枪的子对象并移动至枪口开火的合理位置。
5.准心设置,添加一个UI-Image,命名为RawImage,将准心贴图放入里面,然后移动到合理位置。
6.创建枪开火代码命名为 guncontral 赋予到枪上
7.将枪口火焰与子弹关联到代码中
8.在代码中写出子弹数,生成位置,开火间隔。
添加换弹动画并在代码中设置R键换弹并关联上。
换弹停止射击我将实际开火时间设置为 timer = -1.5f; 。
9.子弹数目展示,新建一个UI-Legacy-text,并将它放入左下角
代码内容为:
public class guncontral : MonoBehaviour
{
//枪口火焰生成位置
public Transform firepoint;
//枪口火焰物体
public GameObject fireper;
//子弹生成位置
public Transform bulletpoint;
//子弹物体
public GameObject bulletper;
//子弹个数
private int bulletCount = 42;
// 开火间隔
private float cd = 0.099999f;
//实际开火的时间 计时器
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)
{
timer = -1.5f;
//Invoke("Reload", 2.0f);
GetComponent<Animator>().SetTrigger("Reload");
Reload();
}
if (Input.GetKeyDown(KeyCode.R ) && bulletCount != 42)
{
timer = -1.5f;
GetComponent<Animator>().SetTrigger("Reload");
Reload();
}
}
void Reload()
{//换弹
bulletCount = 42;
bulletcount.text = "子弹数:" + bulletCount;
}
}