目录
目录
1.原理 通过代码生成物体并从枪械射出
展示画面
2.实现过程
1.创建枪械
将准备好的枪械模型导入并移动至摄像机的列表下
2.创建小球
在左栏右键-3D Obect-Sphere创建小球
将小球设置到合适大小后拖入资源栏并删除本体
3.创建UI
左栏右键-UI-Image添加UI图片
按住Alt点击居中
枪械准备动作基本完成
3.代码导入
给枪械创建代码
在最上方添加一栏
using UnityEngine.UI;
以控制UI
创建以下代码
//枪口火焰生成位置
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;
开火间隔与个数可自行根据调节
//创建生成位置 public Transform firepoint; //创建物体 public GameObject fireper;
创建后会在代码区域出现创建物体选项
开火代码为
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();
}
}
Ctrl+s保存代码后返回unity
将准备好的开火动画和音频拖入代码栏
至此,即可实现左键开火射击
4.总结
通过代码即可实现开火,资源物体可以自己挑选。
1.完整代码:
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();
}
}