用Unity制做贪吃蛇小游戏

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

相关文章
相关标签/搜索