在unity2d中为敌人射击冷却时间
Shooting cooldown for enemy in unity2d
我正在统一做一个自上而下的射击游戏,我试图让敌人在看到玩家时开枪。到目前为止,这是我的代码:
public class EnemyShooting : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 20f;
public FieldOfView _fieldofview;
void Start()
{
_fieldofview = FindObjectOfType<FieldOfView>();
}
// Update is called once per frame
void Update()
{
if(_fieldofview.canSeePlayer)
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb2d = bullet.GetComponent<Rigidbody2D>();
rb2d.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
然而,当检测到玩家时,它只是发送垃圾邮件,因为它没有冷却计时器。我已经尝试使用协程和 Invoke 方法,但它不起作用。有什么想法吗?
下面的代码定义了两次。当前冷却时间和射击冷却时间。加上底部,你的问题就解决了
public float shootCooldown = 5; // 5sec for e.g.
private float currentCooldown;
void Update()
{
if (currentCooldown > 0) // If shoot not in cooldown
{
currentCooldown = shootCooldown; // Set current cooldown time to shootCooldown
if(_fieldofview.canSeePlayer) Shoot();
}
else currentCooldown -= Time.deltaTime; // Reduce cooldown over time
}
我正在统一做一个自上而下的射击游戏,我试图让敌人在看到玩家时开枪。到目前为止,这是我的代码:
public class EnemyShooting : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 20f;
public FieldOfView _fieldofview;
void Start()
{
_fieldofview = FindObjectOfType<FieldOfView>();
}
// Update is called once per frame
void Update()
{
if(_fieldofview.canSeePlayer)
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb2d = bullet.GetComponent<Rigidbody2D>();
rb2d.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
}
}
然而,当检测到玩家时,它只是发送垃圾邮件,因为它没有冷却计时器。我已经尝试使用协程和 Invoke 方法,但它不起作用。有什么想法吗?
下面的代码定义了两次。当前冷却时间和射击冷却时间。加上底部,你的问题就解决了
public float shootCooldown = 5; // 5sec for e.g.
private float currentCooldown;
void Update()
{
if (currentCooldown > 0) // If shoot not in cooldown
{
currentCooldown = shootCooldown; // Set current cooldown time to shootCooldown
if(_fieldofview.canSeePlayer) Shoot();
}
else currentCooldown -= Time.deltaTime; // Reduce cooldown over time
}