在Unity中设置武器的射速



我试图在Unity中设置一个射击速率,这样当我按住箭头时,我将每1秒发射一次炮弹。目前,我的代码每帧更新一次,即使我有一个协程设置。

public GameObject bulletPrefab;
public float bulletSpeed;
public float fireRate = 1f;
public bool allowFire = true;   
void Update()
{
//shooting input
if (Input.GetKey(KeyCode.UpArrow) && allowFire == true)
{
StartCoroutine(Shoot("up"));
}

}
IEnumerator Shoot(string direction)
{
allowFire = false;
if (direction == "up")
{
var bulletInstance = Instantiate(bulletPrefab, new Vector3(transform.position.x, transform.position.y, transform.position.z + 1), Quaternion.identity);
bulletInstance.GetComponent<Rigidbody>().AddForce(Vector3.forward * bulletSpeed);
}
yield return new WaitForSeconds(fireRate);
allowFire = true;
}

协程

你可以使用协程,但是因为你是在Update循环中调用它,所以你需要等待它完成后再开始另一个。

Coroutine currentCoroutine;

if(currentCoroutine == null)
currentCoroutine = StartCoroutine(DoShoot());
IEnumerator DoShoot() {
// Shoot.
yield return new WaitForSeconds(1f);
currentCoroutine = null;
}

时间戳你也可以使用时间戳来表示冷却时间准备好了。它基本上是当前时间加上一些持续时间。

float cooldown = 1f;
float cooldownTimestamp;
bool TryShoot (Vector2 direction) {
if (Time.time < cooldownTimestamp) return false;
cooldownTimestamp = Time.time + cooldown;
// Shoot!
}

我通常会这样做:

<<p>变量/strong>
[Serializefield] float shootDelay = 1f;  
float T_ShootDelay

Start ()

T_ShootDelay = shootDelay;  

Update ()

if(T_ShootDelay < shootDelay)
T_ShootDelay += Time.deltaTime;

ShootInput ()

if(T_ShootDelay >= shootDelay)
{
T_ShootDelay = 0;
Shoot();
}  

  • 检查shootDelay定时器是否小于shootDelay。
  • 将计时器每秒加1。
  • 每次要拍摄时检查定时器状态
  • 拍摄后设置定时器为0

考虑每分钟至少发射700发子弹的M4 AR。

700发/60(秒)~= 11,66发/秒

1秒/11轮~= 0.085秒每轮之间的延迟

你可以简单地试试:

yield return new WaitForSeconds(1 / (fireRate / 60f));

最新更新