我的敌人射击有这个问题,你看,我在用光线投射来探测我的玩家在哪里,一旦发现我想让敌人射击,到目前为止我已经做到了,但是每颗实例化的子弹之间没有延迟!所以子弹是不断地射出,而不是在每个产卵之间延迟。我已经尝试了很多不同的解决方案来解决这个问题,但是没有什么效果!我已经尝试过IEnumerator、对象池、创建一个倒计时和调用&调用,但是我的子弹仍然立即被实例化,没有任何延迟。有谁知道如何在每个实例化的子弹之间延迟吗??谢谢!
这是我的剧本:
public GameObject bulletPrefab;
public Transform bulletSpawn;
public Transform sightStart, sightEnd;
public bool spotted = false;
void Update()
{
RayCasting ();
Behaviours ();
}
void RayCasting()
{
Debug.DrawLine (sightStart.position, sightEnd.position, Color.red);
spotted = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer("Player"));
}
void Behaviours()
{
if (spotted == true) {
//Invoke("Fire", cooldownTimer);
Fire ();
} else if (spotted == false) {
//CancelInvoke ();
}
}
void Fire()
{
GameObject bullet = (GameObject)Instantiate (bulletPrefab);
//GameObject bullet = objectPool.GetPooledObject ();
bullet.transform.position = transform.position;
bullet.GetComponent<Rigidbody2D> ().velocity = bullet.transform.up * 14;
Destroy (bullet, 2.0f);
}发布于 2017-05-13 17:00:11
你需要控制子弹产生的速度。你可以基于帧的数量,但这是一个糟糕的方法,因为射击率将随着游戏的表现而变化。
一个更好的方法是使用一个变量来跟踪我们需要多少时间才能再次开火。我称之为“下一次拍摄时间”(TTNS)
就像..。
private float fireRate = 3f; // Bullets/second
private float timeToNextShot; // How much longer we have to wait.
// [Starts at zero so our first shot is instant]
void Fire() {
// Subtract the time elapsed (since the last frame) from TTNS .
timeToNextShot -= time.deltaTime;
if(timeToNextShot <= 0) {
// Reset the timer to next shot
timeToNextShot = 1/fireRate;
//.... Your code
GameObject bullet = (GameObject)Instantiate (bulletPrefab);
//GameObject bullet = objectPool.GetPooledObject ();
bullet.transform.position = transform.position;
bullet.GetComponent<Rigidbody2D> ().velocity = bullet.transform.up * 14;
Destroy (bullet, 2.0f);
}
}这确实假设每个帧只调用Fire()一次(否则将多次从nextShot中减去经过的时间)。
我选择了这样做(从时间跨度中减去切片),而不是定义一个绝对时间(直到time.elapsedTime > x),因为elapsedTime的分辨率会随着时间的推移而降低,这种方法会在游戏播放几个小时后导致故障。
https://stackoverflow.com/questions/43955288
复制相似问题