網頁連結
多人連線遊戲的一個常見特徵是玩家可以發射子彈,並且讓這些子彈在遊戲中的每一個用戶端上執行。
本次的教學將會增加射擊功能,但是會先製作單機版本,非連線模式,下一篇的教學才會包含網路環境下的射擊。
- 新增一個Sphere物件
- 將它重新命名為Bullet
- 選擇Bullet物件,修改scale數值為(0.2, 0.2, 0.2)
- 在Bullet下新增元件Physics->Rigidbody
- 將Rigidbody下的Use Gravity設為false
- 拖曳Bullet至Project視窗下的prefab資料夾,將Bullet設為prefab物件
- 刪除場經中的Bullet
PlayerController腳本先在需要新增射擊功能,此腳本需要參考Bullet prefab,並由一段程式碼完成射擊功能。
添加Bullet prefab的GameObject變數:
public GameObject bulletPrefab;
添加Bullet生成位置變數:
public Transform bulletSpawn;
在Update中添加以下的判斷式:
if (Input.GetKeyDown(KeyCode.Space))
{
Fire();
}
新增一個Fire函式來發射子彈:
void Fire()
{
// Create the Bullet from the Bullet Prefab
GameObject bullet = (GameObject)Instantiate (
bulletPrefab,
bulletSpawn.position,
bulletSpawn.rotation);
// Add velocity to the bullet
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 6;
// Destroy the bullet after 2 seconds
Destroy(bullet, 2.0f);
}