我正在統一進行自上而下的射擊游戲,我試圖讓敵人看到玩家時射擊。到目前為止,這是我的代碼:
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);
}
}
但是,當檢測到玩家時,它只會向子彈發送垃圾郵件,因為它沒有冷卻計時器。我已經嘗試過使用 Coroutine 和 Invoke 方法,但它不起作用。有任何想法嗎?
uj5u.com熱心網友回復:
下面的代碼定義了兩次。當前的冷卻時間和射擊冷卻時間。添加底部,您的問題將得到解決。
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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/480218.html