1.新建一个2D项目,导入资源包,创建好Assets目录下的子文件夹
2.创建一个3D Object里的Quad用作游戏的背景,将它重命名为BG,将它的尺寸设置为:
3.利用Cube创建蛇头和蛇身,重命名为SnakeHead、SnakeBody,并赋上材质,将SnakeBody拖动到Prefabs中,为它编写一个脚本来控制蛇头,蛇身的移动。代码如下:
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);
}
}
}
蛇头的参数设置:
蛇身的参数设置:
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 () {
}
}
食物的参数设置:
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.摄像机的参数设置:
来源:oschina
链接:https://my.oschina.net/u/4462205/blog/3214590