Unity Artificial Intelligence Programming
上QQ阅读APP看书,第一时间看更新

Shooting bullet

Whenever the player clicks the left mouse button, we check whether the total elapsed time since the last fire has passed the fire rate of the weapon. If it has, then we create a new Bullet object at the SpawnPoint variable's position. In this way, we can prevent the player from shooting a continuous stream of bullets:

    void UpdateWeapon() 
    { 
      if (Input.GetMouseButtonDown(0)) 
      { 
        elapsedTime += Time.deltaTime; 
        if (elapsedTime >= shootRate) 
        { 
          //Reset the time 
          elapsedTime = 0.0f; 
 
          //Instantiate the bullet 
          Instantiate(Bullet, bulletSpawnPoint.position,  
          bulletSpawnPoint.rotation); 
        } 
      } 
    }