1. 程式人生 > >Unity實戰 RTS3D即時戰略遊戲開發(十一) 單位生產

Unity實戰 RTS3D即時戰略遊戲開發(十一) 單位生產

      大家好,我是Zander,我們接著來開發Rts3D即時戰略遊戲開發。在 遊戲中我們要建築也能生產無人機,這一章我們就來實現一下具體操作。

      首先在Actions資料夾下建立CreateUnitAction指令碼並編輯,如下:

using UnityEngine;
using System.Collections;

public class CreateUnitAction : ActionBehavior {

	public GameObject Prefab;  //生產單位
	public float Cost = 0;     //生產單位所需金幣
	private PlayerSetupDefinition player;//所屬玩家資訊

	// Use this for initialization
	void Start () {
		player = GetComponent<Player> ().Info;
	}
	
	public override System.Action GetClickAction ()
	{
		return delegate() {
			if (player.Credits < Cost) {
				Debug.Log ("Cannot Create, It costs " + Cost);
				return;
			}

			var go = (GameObject)GameObject.Instantiate (
				         Prefab,
				         transform.position,
				         Quaternion.identity);
			go.AddComponent<Player> ().Info = player;
			go.AddComponent<RightClickNavigation> ();
			go.AddComponent<ActionSelect> ();
			player.Credits -= Cost;
		};
	}
}
切換到FindBuildingSite指令碼,在Update函式下,新增以下程式碼:
void Update () {
		var tempTarget = RtsManager.Current.ScreenPointToMapPosition (Input.mousePosition);
		if (tempTarget.HasValue == false)
			return;

		transform.position = tempTarget.Value;

		if (Vector3.Distance (transform.position, Source.position) > MaxBuildDistance) {
			rend.material.color = Red;
			return;
		}

		if (RtsManager.Current.IsGameObjectSafeToPlace (gameObject)) {
			rend.material.color = Green;
			if (Input.GetMouseButtonDown (0)) {
				var go = GameObject.Instantiate (BuildingPrefab);
				go.AddComponent<ActionSelect> ();   //增加選擇動作
				go.transform.position = transform.position;
				Info.Credits -= Cost;
				go.AddComponent<Player> ().Info = Info;
				Destroy (this.gameObject);
			}
		} else {
			rend.material.color = Red;
		}
	}

然後返回的Unity中,在Prefabs資料夾下找到Command Base預設,為其新增CreateBuildingAction元件,併為其賦值,如圖所示


現在就可以自動生產無人機了。

   好了,這一章就寫到這,接下來的幾張我將為大家介紹一下AI。歡迎大家加入QQ群:280993838  或者關注我的公眾號: