代码
方块随机产生(FoodCreate)
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 () {
}
}
控制贪吃蛇移动(snakemove)
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.D) || (Input.GetKeyDown(KeyCode.RightArrow)))
{
direction = Vector2.right;
}
else if (Input.GetKeyDown(KeyCode.A) || (Input.GetKeyDown(KeyCode.LeftArrow)))
{
direction = Vector2.left;
}
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.CompareTag("Food"))
{
Destroy(other.gameObject);
flag = true;
}
else
{
SceneManager.LoadScene("LoadGame");
}
}
}
游戏失败后点击重新开始游戏(SnakeUI)
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.1");
}
}
}
步骤
(导入素材包)或者 (自己造材质)
1.新建cube物体来制作蛇头和食物,赋给它们不同的材质加以区分。
2.新建quad物体来制作背景,调整大小,在quad里面再制造四个空物体,调整大小,分别将背景四边墙住,为了让蛇头碰到后游戏结束。
3.添加一个Directional light。
4.给蛇头加上刚体,取消重力,把代码(snakemove)加赋给蛇头,把snakebody材质对象赋值给snakemovedaim里的snakebody。
5.把FoodCreate代码赋给摄像机,并将Food材质对象赋给S_food。
6.保存这个场景作为(游戏场景),并在选项栏里找到file,找到里面的build settings选项,点击右边中部add open scenes,将游戏场景添加。
7.新建一个场景,当做死亡场景,添加文本(也就是右键-UI-text),会出现包含text的Canvas物体和EventSystem物体,点击text,修改其中的文本来提示玩家,用鼠标点击才能重新回到游戏页面,调整文本颜色。(也能自己修改其中的属性)
8.将(SnakeUI)代码赋给text.
9.保存死亡场景,和游戏场景一样在build settings里面添加。
10.运行并查看是否有错误。