1.新建一個2D項目,導入資源包,建立好Assets目錄下的子文件夾dom
2.建立一個3D Object裏的Quad用做遊戲的背景,將它重命名爲BG,將它的尺寸設置爲:ide
3.利用Cube建立蛇頭和蛇身,重命名爲SnakeHead、SnakeBody,並賦上材質,將SnakeBody拖動到Prefabs中,爲它編寫一個腳原本控制蛇頭,蛇身的移動。代碼以下:this
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; using UnityEngine.SceneManagement; public class SnakeMove : MonoBehaviour { List<Transform> body=new List<Transform>(); Vector2 direction=Vector2.up; public GameObject snakeBody; private bool flag; float speed=0.3f; void Move(){ Vector2 position=transform.position; if(flag) { GameObject bodypfb=(GameObject)Instantiate(snakeBody,position,Quaternion.identity); body.Insert(0,bodypfb.transform); flag=false; } else if(body.Count>0) { body.Last().position=position; body.Insert(0,body.Last().transform); body.RemoveAt(body.Count-1); } this.transform.Translate(direction); } // Use this for initialization void Start () { InvokeRepeating("Move",speed,speed); } // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.W) || (Input.GetKeyDown(KeyCode.UpArrow))) { direction=Vector2.up; } else if(Input.GetKeyDown(KeyCode.S) || (Input.GetKeyDown(KeyCode.DownArrow))) { direction=Vector2.down; } else if(Input.GetKeyDown(KeyCode.A) || (Input.GetKeyDown(KeyCode.LeftArrow))) { direction=Vector2.left; } else if(Input.GetKeyDown(KeyCode.D) || (Input.GetKeyDown(KeyCode.RightArrow))) { direction=Vector2.right; } } void OnTriggerEnter(Collider coll) { if(coll.gameObject.CompareTag("food")) { Destroy(coll.gameObject); flag=true; } else { SceneManager.LoadScene(0); } } }
蛇頭的參數設置:code
蛇身的參數設置:orm
4.利用Cube建立食物,重命名爲Food,並賦上材質,將它拖到Prefabs中,爲它編寫一個腳原本控制食物的生成。代碼以下:對象
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FoodCreate : MonoBehaviour { public GameObject s_food; public int x_limit=30; public int y_limit=16; void Food() { int x=Random.Range(-x_limit,x_limit); int y=Random.Range(-y_limit,y_limit); Instantiate(s_food,new Vector2(x,y),Quaternion.identity); } // Use this for initialization void Start () { InvokeRepeating("Food",2,3); } // Update is called once per frame void Update () { } }
食物的參數設置:blog
5.在BG裏建立4個Empty對象,並將它們重命名爲Left,Right,Top,Bottom,同時給它們添加一個Box Collider,調整位置及大小以下:遊戲
6.爲遊戲場景建立一個UI界面資源
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SnakeUI : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetMouseButtonDown(0)) { SceneManager.LoadScene(1); } } }
7.攝像機的參數設置:it