Unity2D:敌人射击

时间:2017-05-13 16:12:29

标签: c# unity3d

我在敌人射击时遇到这个问题,你看我正在使用光线投射来探测我的玩家在哪里,一旦被发现我想要敌人射击,到目前为止我已经完成了但是每次之间没有延迟实例化的子弹!因此子弹不断产生而不是每个产卵之间的延迟。我已经尝试了很多不同的解决方案来解决这个问题,但没有任何效果!我已经尝试过IEnumerator,对象池,创建倒计时器并调用& invokerepeating但仍然我的子弹仍然立即被实例化,没有任何延迟。有没有人知道如何在每个实例化的子弹之间有延迟?谢谢!

这是我的剧本:

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);
}

1 个答案:

答案 0 :(得分:1)

你需要限制子弹产生的速度。你可以以帧数为基础,但这是一个不好的方法,因为火率会因游戏性能而异。

更好的方法是使用变量来跟踪在我们再次开火之前必须经过多长时间。我打电话给这个&#34; Time To Next Shot&#34; (TTNS)

  • 在已经消失的时间内减少TTNS。
  • 检查TTNS是否为0
  • 如果是这样的话:
    • 根据我们所需的射速设置TTNS。
    • 射击

像...这样的东西。

private float fireRate = 3f; // Bullets/second
private float timeToNextShot; // How much longer we have to wait.

void Fire() {       
        // Subtract the time since the last 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&gt; x),因为elapsedTime的分辨率会随着时间的推移而减小,这种方法将会经过几个小时的游戏后会出现故障。

相关问题