一、游戏运行界面
游戏规则:当蛇头每吃到一块食物,蛇身会长一截;当蛇头碰到蛇身或者四周墙壁时,游戏结束。
二、食物自动生成脚本(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 () {
}
}
三、控制蛇头移动脚本(sneakMove)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.SceneManagement;
public class SneakMove : MonoBehaviour {
List<Transform> body = new List<Transform>();
//蛇身
Vector2 direction = Vector2.up;
public GameObject snakwbody;
private bool flag;
float speed = 0.3f;
//蛇头自动向前
void Move()
{
Vector2 position = transform.position;
if(flag)
{
//长身体
GameObject bodypfb = (GameObject)Instantiate(snakwbody, 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
//WASD/上下左右来控制蛇头方向
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);
}
}
}
四、切换场景脚本,游戏失败返回首页。
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);
}
}
}
来源:oschina
链接:https://my.oschina.net/u/4462184/blog/3217673