1.先创建基本场景、枪、子弹。
2.点击右上角GaneObject选择3D Object创建一些物体。
3.搭建一个场景,也可以去下载现成的模型。
4.创建一个胶囊体当人物,下载一把枪的模型
5.调整好枪的角度和位置,再在游戏画面中添加准心
触发射击后,我们会在指定位置实例化子弹的实体,并使之向固定方向移动。
首先我们创建子弹实体的预制件,记得要添加rigidbody组件。
6.再创建c# 代码
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;
}
}
代码添加完成后点击运行即可射击,按r键即可换弹。
射击功能已经实现完成 。