好,我知道你想要做什么,所以我来帮你进行一下:
public class yourgun : MonoBehaviour
{
// 这里是涉及射击的代码
private void Update()
{
// debug用来测试射击的范围
Debug.DrawRay(transform.position, -transform.right * range, Color.red);
// 检测是否按下鼠标左键
if (Input.GetKey(KeyCode.Mouse0))
{
// 降低弹药数量
ammo--;
Debug.Log(ammo);
// 开始射击
ray = new Ray(transform.position, transform.forward);
ray = Cam.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
if (Physics.Raycast(ray, out hit))
{
// 检测目标是否是"Player"
if (hit.collider.CompareTag("Player"))
{
// 如果是就设置玩家对象
player = hit.collider.gameObject;
health = player.GetComponent<Health>();
// 伤害玩家
health.health -= damage;
Debug.Log(health.health);
Debug.Log("Hit!");
// 如果玩家生命值为0就销毁玩家
if (health.health == 0)
{
Destroy(hit.collider.gameObject);
health.health = 0;
}
}
}
}
// 重置弹药
Reload();
}
private void Reload()
{
// 弹药数量小于等于最低弹药数量就使用最低弹药
if (ammo <= minammo)
{
ammo = minammo;
// 检测是否按下R键
if (Input.GetKey(KeyCode.R))
{
// 使用最大弹药
ammo = maxammo;
Debug.Log("当前弹药数量是:" + ammo);
}
}
}
}
答案是可以的。首先是你要设置一个最低或上限的射速或者你也可以在这里做一个计时器当计时完就发射一个弹。
如果你要减少射速你可以如下代码:
private float fireRate = 1.0f; // 发射器每秒速度
private float lastFireTime; // 上次发射时间
void fire()
{
// 弹药数量小于等于最小弹药
if (ammo <= minammo)
{
// 停止发射
return;
}
// 如果上次发射时间小于当前时间减去发射器每秒速度,那么我们就开始发射
if (lastFireTime && Time.time - lastFireTime < fireRate)
{
return;
}
// 开始发射
else
{
// 写你的发射代码这里
ray = new Ray(transform.position, transform.forward);
ray = Cam.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
if (Physics.Raycast(ray, out hit))
{
// 写你的射击代码这里
}
}
// 记录上次发射时间
lastFireTime = Time.time;
// 使用减少一次弹药
ammo--;
}
这就是答案了。
评论 (0)