界面
设置Canvas
UI层默认在最上面,但是为了让2D物体与UI同层,需要设置Canvas
选择Canvas
Render Camera拖入默认摄像机
添加阴影和描边
创建单选框
创建两个Toggle做成互斥
将两个Toggle放入一个父级里,父级添加Toggle Group
Allow Switch off这个如果不勾选,它子物体,两个单选就必须要选着一个
选中Toggle
is On 是默认开局勾选
Group 组,拖入父对象
两个Toggle就在一个组里,相斥
生成食物
创建空物体要注意选中Canvas,在Canvas里面创建空物体,再将空物体放大至全屏。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FoodMake : MonoBehaviour
{
private static FoodMake _instance;
public static FoodMake Instance
{
get
{
return _instance;
}
}
public int xlimit = 9;//屏幕右边的步数
public int ylimit = 5;//屏幕左边的步数
public int xoffset = 5; //屏幕右边的步数减去左边的步数
public GameObject foodPrefab; //食物的预设体
//public GameObject RewardPrefab;
public Sprite[] foodSprites;//定义一个数组
private Transform foodHolder;//定义一个食物位置
void Awake()
{
_instance = this;
}
void Start()
{
foodHolder = GameObject.Find("FoodHolder").transform;//获取空物体位置
Makefood(false);
}
public void Makefood(bool isReward)
{
int index = Random.Range(0, foodSprites.Length);//index随机值,foodSprite.length数字中最大值
GameObject food = Instantiate(foodPrefab);//Instantiate实例化的方法
food.GetComponent<Image>().sprite = foodSprites[index];//sprite在food数组中随机
food.transform.SetParent(foodHolder, false);//定位到FoodHolder
int x = Random.Range(-xlimit + xoffset, xlimit);
int y = Random.Range(-ylimit, ylimit);
food.transform.localPosition = new Vector3(x * 30, y * 30, 0);
}
}
贪吃蛇头
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SnakeHead : MonoBehaviour
{
public List< Transform > bodyList = new List< Transform >();//蛇身
public float velocity = 0.35f;//定义蛇头的移动速度
public int step = 30;//定义蛇每次移动距离
private int x, y;//蛇下次要移动的位置,也就是增量
private Vector3 headPos;//蛇头的位置
private Vector3 HPos;//定义全局变量
private Transform canvas;
public GameObject bodyPrefab;//身体预制体
public Sprite[] bodySprites = new Sprite[2];//身体数组
private bool isDie = false;
public GameObject dieEffect;
void Awake()
{
canvas = GameObject.Find("Canvas").transform;//获取canvas
//通过Resources.Load(string path)方法加载资源,path的书写不需要加Resources/以及文件扩展名
//gameObject.GetComponent<Image>().sprite = Resources.Load<Sprite>(PlayerPrefs.GetString("sh", "sh02"));
//bodySprites[0] = Resources.Load<Sprite>(PlayerPrefs.GetString("sb01", "sb0201"));
//bodySprites[1] = Resources.Load<Sprite>(PlayerPrefs.GetString("sb02", "sb0202"));
}
void Start()
{
InvokeRepeating("move", 0, velocity);//InvokeRepeating 反复调用的方法 语法格式:InvokeRepeating("调用方法",间隔时长,速度)
x = step; y = 0;//一出生就向右移动
gameObject.transform.localRotation = Quaternion.Euler(0, 0, -90);//一出生也旋转到右
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
CancelInvoke();//暂停调用
InvokeRepeating("move", 0, velocity - 0.2f);//开始调用
}
if (Input.GetKeyUp(KeyCode.Space))
{
CancelInvoke();
InvokeRepeating("move", 0, velocity);
}
if (Input.GetKey(KeyCode.W) && y != -step)
//按键判断按键,和Y轴不等于-的值(如果向下移动值就负的不能向上移动)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, 0);//Quaternion四元数的方法,可传x,y,z三个轴向的角度
x = 0; y = step;
}
if (Input.GetKey(KeyCode.S) && y != step)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, 180);
x = 0; y = -step;
}
if (Input.GetKey(KeyCode.A) && x != step)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, 90);
x = -step; y = 0;
}
if (Input.GetKey(KeyCode.D) && x != -step)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, -90);
x = step; y = 0;
}
}
void move()
{
headPos = gameObject.transform.localPosition;//保存下来蛇头移动前的位置
gameObject.transform.localPosition = new Vector3(headPos.x + x, headPos.y + y, headPos.z);//蛇头向期望位置移动
if (bodyList.Count > 0)//至少有一个身体长度才执行
{
for (int i = bodyList.Count - 2; i >= 0; i--)//从后往前开始移动蛇身
{
bodyList[i + 1].localPosition = bodyList[i].localPosition;//每一个蛇身一到那个倒他前一个节点位置
}
bodyList[0].localPosition = headPos;//第一个蛇身移动到之前蛇头的位置
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("food"))
{
Destroy(collision.gameObject);
MainUI.Instance.UpdateUI();//实例另一个脚本代码的一个方法
Grow();
FoodMake.Instance.Makefood((Random.Range(0, 100) < 20) ? true : false);
}
else if (collision.gameObject.CompareTag("Body"))
{
Debug.Log("si");
Die();
}
}
void Grow()//生成身体
{
int index = (bodyList.Count % 2 == 0) ? 0 : 1;
GameObject body = Instantiate(bodyPrefab, new Vector3(2000, 2000, 0), Quaternion.identity);
body.GetComponent<Image>().sprite = bodySprites[index];
body.transform.SetParent(canvas, false);//生成在canvas里
bodyList.Add(body.transform);
}
void Die()
{
CancelInvoke();
isDie = true;
Instantiate(dieEffect);
PlayerPrefs.SetInt("lastl", MainUI.Instance.length);
PlayerPrefs.SetInt("lasts", MainUI.Instance.score);
if (PlayerPrefs.GetInt("bests", 0) < MainUI.Instance.score)
{
PlayerPrefs.SetInt("bestl", MainUI.Instance.length);
PlayerPrefs.SetInt("bests", MainUI.Instance.score);
}
StartCoroutine(GameOver(1.5f));
}
IEnumerator GameOver(float t)
{
yield return new WaitForSeconds(t);
UnityEngine.SceneManagement.SceneManager.LoadScene(1);
}
}
MainUI
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MainUI : MonoBehaviour
{
private static MainUI _instance;
public static MainUI Instance
{
get
{
return _instance;
}
}
public bool hasBorder = true;
public bool isPause = false;//暂停
public int score = 0;
public int length = 0;
public Text msgText;
public Text scoreText;//分数
public Text lengthText;//长度
public Sprite[] pauseSprites;
public Image bgImage;
public Image PauseButton;//暂停按钮
void Awake()
{
_instance = this;
}
void Start()
{
if (PlayerPrefs.GetInt("border", 1) == 0)
{
hasBorder = false;
foreach (Transform t in bgImage.gameObject.transform)
{
t.gameObject.GetComponent<Image>().enabled = false;
}
}
}
public void UpdateUI(int s = 5, int l = 1)
{
//吃一个食物
score += s;//加5分
length += l;//加1长度
scoreText.text = "得分:\n" + score;
lengthText.text = "长度:\n" + length;
}
public void Pause()//暂停
{
isPause = !isPause;
if (isPause)
{
Time.timeScale = 0;
PauseButton.sprite = pauseSprites[0];
}
else
{
Time.timeScale = 1;
PauseButton.sprite = pauseSprites[1];
}
}
public void Home()
{
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
}
StartUIControlle
开始界面的代码,给scoreHolder空物体
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class StartUIController : MonoBehaviour
{
public Text lastText;
public Text bestText;
void Awake()
{
lastText.text = "上次:长度" + PlayerPrefs.GetInt("lastl", 0) + ",分数" + PlayerPrefs.GetInt("lasts", 0);
bestText.text = "最好:长度" + PlayerPrefs.GetInt("bestl", 0) + ",分数" + PlayerPrefs.GetInt("bests", 0);
}
public void StartGame()
{
UnityEngine.SceneManagement.SceneManager.LoadScene(1);
}
}