用unity制作贪吃蛇小游戏

丶灬走出姿态 提交于 2020-04-06 12:36:10

一、游戏运行界面

游戏规则:当蛇头每吃到一块食物,蛇身会长一截;当蛇头碰到蛇身或者四周墙壁时,游戏结束。

二、食物自动生成脚本(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);
    }
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!