1、在unity3d中創建新的項目,在新項目中創建Plane作為地面,根據自己的需求調整Plane的大小,同時給Plane添加Materials,這樣易於區分地面與其他游戲物體區別;創建Directional light照亮游戲世界。
2、在有游戲中添加兩個Cube,添加CharacterController組件,一個命名為player,另一個命名為enemy,把它們的Layer設為Default;
3、在player下創建Quad作為子對象,把它的Layer設為UI;把Quad的Transform的Rotation的x設置為90;Position的y值設置一個大於10的數(不要太大);這樣在player的正上方就會有圖標。


4、對enemy做和player的一樣處理,然后copy10個左右數量的enemy隨機的放到不同的位置。

5、在游戲中創建新Camera對象,把它作為player的子對象;調整Camera的位置和角度,讓Camera在player的正上方俯視player。設置Camera的Culling Mask屬性,把Default的勾去掉。設置ViewportRect的屬性,X和Y是Camera投影到屏幕的原點(左下點為(0,0)點);W和H投影尺寸的寬和高。


6、把Main Camera做為player的子對象調整位置和角度,設置Main Camera的Culling Mask屬性,把UI的勾去掉;分別給player、enemy添加腳本PlayerMove、EnemyMove;
using UnityEngine; using System.Collections; public class PlayerMove : MonoBehaviour { private CharacterController controller; // Use this for initialization void Start() { controller = this.GetComponent<CharacterController>(); } // Update is called once per frame void Update() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); Vector3 v1 = new Vector3(h, 0, v); controller.SimpleMove(v1 * 30.0f); } }
using UnityEngine;
using System.Collections;
public class EnemyMove : MonoBehaviour
{
private CharacterController controller;
float timer = 0;//控制敵人改變方向的計時器
// Use this for initialization
void Start()
{
controller = this.GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
//敵人每3秒改變一次前進方向
if (timer > 3)
{
float r = Random.Range(-90, 91);//敵人的旋轉角度在-90~90度隨機取值
transform.rotation = Quaternion.Euler(0, r, 0);
timer = 0;
}
else
{
controller.SimpleMove(transform.forward * 15);
timer += Time.deltaTime * 1.0f;
}
}
}
