01-分数与长度的记录以及背景颜色的切换
新建MainUI脚本,挂载在ScriptsHolder下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainUI : MonoBehaviour
{
private static MainUI _instance;
public static MainUI Instance
{
get
{
return _instance;
}
}
public int score = 0;
public int length = 0;
public Text scoreText;
public Text msgText;
public Text lengthText;
public Image bgImage;
private Color tempColor;//接收值
private void Awake()
{
_instance = this;
}
void Update()
{
switch (score/100)
{
case 3:
ColorUtility.TryParseHtmlString("#CCEEFFFF",out tempColor);//尝试解析一个值,并输出值
bgImage.color = tempColor;
msgText.text = "阶段" + 2;
Debug.Log("阶段2转换");
break;
case 5:
ColorUtility.TryParseHtmlString("#CCFFDBFF", out tempColor);
bgImage.color = tempColor;
msgText.text = "阶段" + 3;
break;
case 7:
ColorUtility.TryParseHtmlString("#EBFFCCFF", out tempColor);
bgImage.color = tempColor;
msgText.text = "阶段" + 4;
break;
case 9:
ColorUtility.TryParseHtmlString("#FFF3CCFF", out tempColor);
bgImage.color = tempColor;
msgText.text = "阶段" + 5;
break;
case 11:
ColorUtility.TryParseHtmlString("#FFDACCFF", out tempColor);
bgImage.color = tempColor;
msgText.text = "无尽阶段";
break;
}
}
public void UpdateUI(int s=5, int l = 1)
{
score += s;
length += l;
scoreText.text = "得分:\n" + score;
lengthText.text = "长度:\n" + length;
}
}
using System.Collections;
using System.Collections.Generic;
//using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class SnakeHead : MonoBehaviour
{
public List<Transform> bodyList = new List<Transform>();//存储身体的位置
public float velocity=0.35f;//每隔多久要调用,实际就相当于速度
public int step;//小蛇每一步要走的路
private int x;//x和Y都是移动的增量
private int y;
private Vector3 HeadPos;//记录头的位置
private Transform canvas;
public GameObject bodyPrefab;//蛇身预制体
public Sprite[] bodySprites = new Sprite[2];
private void Awake()
{
canvas = GameObject.Find("Canvas").transform;
}
void Start()
{
InvokeRepeating("Move",0,velocity);
x = 0;//刚开始的时候,贪吃蛇就会往上走
y =step;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))//CancelInvoke()取消当前的Invoke
{
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!=-step加这句是蛇头向下的时候不是直接向下的
{
gameObject.transform.localRotation = Quaternion.Euler(0,0,0);//将Float值转换成四元数
x = 0;
y = step;
}
if (Input.GetKey(KeyCode.S)&&y != step)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, 180);//将Float值转换成四元数
x = 0;
y = -step;
}
if (Input.GetKey(KeyCode.A) && x != step)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, 90);//将Float值转换成四元数
x = -step;
y = 0;
}
if (Input.GetKey(KeyCode.D) && x != -step)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, -90);//将Float值转换成四元数
x = step;
y = 0;
}
}
/// <summary>
/// 头部的移动
/// </summary>
void Move()
{
HeadPos = gameObject.transform.localPosition;//保存下来蛇头移动前的位置
gameObject.transform.localPosition = ne