吃豆子游戏
unity3d 做“吃豆子”游戏
豆子地图:
存在文本中【24 行, 38 列】:
左上角: 右上角:
数组下标:【0,0】 数组下标:【0,37】
场景下标:【-37,23】 场景下标:【37,23】
O............X.....XXX.XX............O
.XXXXX.X.X.X.X.XXX...X....XXXX.XXXX.XX
.X.....X...X.XXX.XXX.X.X.XX.....X.X.XX
.X.XXX.XXXXX.......X.X.X.X..X.X.X.X.X.
.........X...XXXXX.X.X.X.XXXX.X.X.X.XX
.X.XXXXX.X.X.XO....X.X.X..X.X.X.X....O
.X.....X.X.X.XXXXX.X.X.XX.X.X.X.X.XXXX
.XXXXX.X.X.X............X.....X......X
O....X.X.X...XXXX XXXX...XXX.X.X.XX.X
XXXX.X...X.X.X X.X.X.X.X.X.XX.X
X......X.X.X.X X.X.X.....X.XX..
XXXXXXXX.X.X.XXXXXXXXXX.X.XXXXX.X....X
XX.X.X.....X.... ......X.......XXXX
XX.X.X.XXX.XXX.XXXXXXX.XX....X..X..XXX
...X.X.XX..X.........X.XXXXXXXX.XX...X
XX.....XXXXXX...XXXXXX.X....OX...XXX.O
OX.X.......XX.X.XX.....XX.XXXXXX..XXXX
.X.XXXXXX.XXX.X.X..XXX.X..............
...X.XX.X.X.X.X.XX.X.X.XXXXX.XXXXXXX.X
X.XX........X.X....X.......X..........
X..X.XX.XXXXX.XX.XXX.X.XXX.XXXXX...XX.
XXXXXXX.......X..X.X.X...X.X.....XXXX.
........XX.XXXXX.....XXX.X...XXX......
O....................................O
左下角 右下角
数组下标:【23,0】 数组下标:【23,37】
场景下标:【-37,-23】 场景下标:【37,-23】
对应下面的场景地图:
场景生成:
var mapAsset : TextAsset; var blockPrefab : Transform; var pelletPrefab : Transform; var superPrefab : Transform; // 25 rows, 38 columns function Awake () { var map = mapAsset.text.Split ("\n"[0]); var v = new Vector3 (); v.y = 1.0; var j_off = map.length / 2.0; // j_off: 12.5 // test print("length:"+map.length); print("j_off:"+j_off); for (var j = 0; j < map.length; j ++) { v.z = (map.length - j - j_off - 1) * 2; var i_off = map[j].length / 2.0; // i_off: 19 // test print("i_off: "+i_off); for (var i = 0; i < map[j].length; i ++) { v.x = (i - i_off) * 2 + 1; if (map[j][i] == "X") { var inst = Instantiate (blockPrefab, v, Quaternion.identity); inst.transform.parent = transform; // test //print(v + ": X"); } else if (map[j][i] == ".") { Instantiate (pelletPrefab, v, Quaternion.identity); // test //print(v + ": ."); } else if (map[j][i] == "O") { Instantiate (superPrefab, v, Quaternion.identity); // test //print(v + ": O"); } } } }
豆子被吃掉:
var scoreDisplay : GUIText; var smallPelletScore = 10; // 小豆子得分 10 var superPelletScore = 100; // 大豆子得分 100 private var score = 0; function Update () { scoreDisplay.text = "Score: " + score; } function OnTriggerEnter (other : Collider) { if (other.name == "BasicPellet(Clone)") score += smallPelletScore; else if (other.name == "SuperPellet(Clone)") score += superPelletScore; Destroy (other.gameObject); }
豆子的移动策略:
var howLong = 1.0; var howFast = 8.0; private var nextUpdate = 0.0; privatevar direction : Vector3; function Update () { if (Time.time > nextUpdate) { nextUpdate = Time.time + (Random.value * howLong); direction = Random.onUnitSphere; // 产生一个随机的点 Vector3 类型 direction.y = 0; direction.Normalize (); // 单位化,模为 1,即长度为 1 direction *= howFast; direction.y = 1.5 - transform.position.y; } var controller = GetComponent(CharacterController); controller.Move(direction * Time.deltaTime); // deltaTime:以秒计算,完成最后一帧的时间(只读)。 }