unity實(shí)現(xiàn)簡(jiǎn)單的貪吃蛇游戲
本文實(shí)例為大家分享了unity實(shí)現(xiàn)簡(jiǎn)單貪吃蛇游戲的具體代碼,供大家參考,具體內(nèi)容如下

SatUIController代碼
using UnityEngine;
using UnityEngine.UI;
public class StartUIController : MonoBehaviour
{
public Text lastText;
public Text bestText;
public Toggle blue;
public Toggle yellow;
public Toggle border;
public Toggle noBorder;
void Awake()
{
lastText.text = "上次:長度" + PlayerPrefs.GetInt("lastl", 0) + ",分?jǐn)?shù)" + PlayerPrefs.GetInt("lasts", 0);
bestText.text = "最好:長度" + PlayerPrefs.GetInt("bestl", 0) + ",分?jǐn)?shù)" + PlayerPrefs.GetInt("bests", 0);
}
void Start()
{
if (PlayerPrefs.GetString("sh", "sh01") == "sh01")
{
blue.isOn = true;
PlayerPrefs.SetString("sh", "sh01");
PlayerPrefs.SetString("sb01", "sb0101");
PlayerPrefs.SetString("sb02", "sb0102");
}
else
{
yellow.isOn = true;
PlayerPrefs.SetString("sh", "sh02");
PlayerPrefs.SetString("sb01", "sb0201");
PlayerPrefs.SetString("sb02", "sb0202");
}
if (PlayerPrefs.GetInt("border", 1) == 1)
{
border.isOn = true;
PlayerPrefs.SetInt("border", 1);
}
else
{
noBorder.isOn = true;
PlayerPrefs.SetInt("border", 0);
}
}
public void BlueSelected(bool isOn)
{
if (isOn)
{
PlayerPrefs.SetString("sh", "sh01");
PlayerPrefs.SetString("sb01", "sb0101");
PlayerPrefs.SetString("sb02", "sb0102");
}
}
public void YellowSelected(bool isOn)
{
if (isOn)
{
PlayerPrefs.SetString("sh", "sh02");
PlayerPrefs.SetString("sb01", "sb0201");
PlayerPrefs.SetString("sb02", "sb0202");
}
}
public void BorderSelected(bool isOn)
{
if (isOn)
{
PlayerPrefs.SetInt("border", 1);
}
}
public void NoBorderSelected(bool isOn)
{
if (isOn)
{
PlayerPrefs.SetInt("border", 0);
}
}
public void StartGame()
{
UnityEngine.SceneManagement.SceneManager.LoadScene(1);
}
}
SnakeHead代碼
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;
private int y;
private Vector3 headPos;
private Transform canvas;
private bool isDie = false;
public AudioClip eatClip;
public AudioClip dieClip;
public GameObject dieEffect;
public GameObject bodyPrefab;
public Sprite[] bodySprites = new Sprite[2];
void Awake()
{
canvas = GameObject.Find("Canvas").transform;
//通過Resources.Load(string path)方法加載資源,path的書寫不需要加Resources/以及文件擴(kuò)展名
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);
x = 0;y = step;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && MainUIController.Instance.isPause == false && isDie == false)
{
CancelInvoke();
InvokeRepeating("Move", 0, velocity - 0.2f);
}
if (Input.GetKeyUp(KeyCode.Space) && MainUIController.Instance.isPause == false && isDie == false)
{
CancelInvoke();
InvokeRepeating("Move", 0, velocity);
}
if (Input.GetKey(KeyCode.W) && y != -step && MainUIController.Instance.isPause == false && isDie == false)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, 0);
x = 0;y = step;
}
if (Input.GetKey(KeyCode.S) && y != step && MainUIController.Instance.isPause == false && isDie == false)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, 180);
x = 0; y = -step;
}
if (Input.GetKey(KeyCode.A) && x != step && MainUIController.Instance.isPause == false && isDie == false)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, 90);
x = -step; y = 0;
}
if (Input.GetKey(KeyCode.D) && x != -step && MainUIController.Instance.isPause == false && isDie == false)
{
gameObject.transform.localRotation = Quaternion.Euler(0, 0, -90);
x = step; y = 0;
}
}
void Move()
{
headPos = gameObject.transform.localPosition; //保存下來蛇頭移動(dòng)前的位置
gameObject.transform.localPosition = new Vector3(headPos.x + x, headPos.y + y, headPos.z); //蛇頭向期望位置移動(dòng)
if (bodyList.Count > 0)
{
//由于我們是雙色蛇身,此方法棄用
//bodyList.Last().localPosition = headPos; //將蛇尾移動(dòng)到蛇頭移動(dòng)前的位置
//bodyList.Insert(0, bodyList.Last()); //將蛇尾在List中的位置更新到最前
//bodyList.RemoveAt(bodyList.Count - 1); //移除List最末尾的蛇尾引用
//由于我們是雙色蛇身,使用此方法達(dá)到顯示目的
for (int i = bodyList.Count - 2; i >= 0; i--) //從后往前開始移動(dòng)蛇身
{
bodyList[i + 1].localPosition = bodyList[i].localPosition; //每一個(gè)蛇身都移動(dòng)到它前面一個(gè)節(jié)點(diǎn)的位置
}
bodyList[0].localPosition = headPos; //第一個(gè)蛇身移動(dòng)到蛇頭移動(dòng)前的位置
}
}
void Grow()
{
AudioSource.PlayClipAtPoint(eatClip, Vector3.zero);
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);
bodyList.Add(body.transform);
}
void Die()
{
AudioSource.PlayClipAtPoint(dieClip, Vector3.zero);
CancelInvoke();
isDie = true;
Instantiate(dieEffect);
PlayerPrefs.SetInt("lastl", MainUIController.Instance.length);
PlayerPrefs.SetInt("lasts", MainUIController.Instance.score);
if (PlayerPrefs.GetInt("bests", 0) < MainUIController.Instance.score)
{
PlayerPrefs.SetInt("bestl", MainUIController.Instance.length);
PlayerPrefs.SetInt("bests", MainUIController.Instance.score);
}
StartCoroutine(GameOver(1.5f));
}
IEnumerator GameOver(float t)
{
yield return new WaitForSeconds(t);
UnityEngine.SceneManagement.SceneManager.LoadScene(1);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Food"))
{
Destroy(collision.gameObject);
MainUIController.Instance.UpdateUI();
Grow();
FoodMaker.Instance.MakeFood((Random.Range(0, 100) < 20) ? true : false);
}
else if (collision.gameObject.CompareTag("Reward"))
{
Destroy(collision.gameObject);
MainUIController.Instance.UpdateUI(Random.Range(5, 15) * 10);
Grow();
}
else if (collision.gameObject.CompareTag("Body"))
{
Die();
}
else
{
if (MainUIController.Instance.hasBorder)
{
Die();
}
else
{
switch (collision.gameObject.name)
{
case "Up":
transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y + 30, transform.localPosition.z);
break;
case "Down":
transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y - 30, transform.localPosition.z);
break;
case "Left":
transform.localPosition = new Vector3(-transform.localPosition.x + 180, transform.localPosition.y, transform.localPosition.z);
break;
case "Right":
transform.localPosition = new Vector3(-transform.localPosition.x + 240, transform.localPosition.y, transform.localPosition.z);
break;
}
}
}
}
}
MainUIController
using UnityEngine;
using UnityEngine.UI;
public class MainUIController : MonoBehaviour
{
private static MainUIController _instance;
public static MainUIController 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 Image pauseImage;
public Sprite[] pauseSprites;
public Image bgImage;
private Color tempColor;
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;
}
}
}
void Update()
{
switch (score / 100)
{
case 0:
case 1:
case 2:
break;
case 3:
case 4:
ColorUtility.TryParseHtmlString("#CCEEFFFF", out tempColor);
bgImage.color = tempColor;
msgText.text = "階段" + 2;
break;
case 5:
case 6:
ColorUtility.TryParseHtmlString("#CCFFDBFF", out tempColor);
bgImage.color = tempColor;
msgText.text = "階段" + 3;
break;
case 7:
case 8:
ColorUtility.TryParseHtmlString("#EBFFCCFF", out tempColor);
bgImage.color = tempColor;
msgText.text = "階段" + 4;
break;
case 9:
case 10:
ColorUtility.TryParseHtmlString("#FFF3CCFF", out tempColor);
bgImage.color = tempColor;
msgText.text = "階段" + 5;
break;
default:
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;
}
public void Pause()
{
isPause = !isPause;
if (isPause)
{
Time.timeScale = 0;
pauseImage.sprite = pauseSprites[1];
}
else
{
Time.timeScale = 1;
pauseImage.sprite = pauseSprites[0];
}
}
public void Home()
{
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
}
FoodMaker代碼
using UnityEngine;
using UnityEngine.UI;
public class FoodMaker : MonoBehaviour
{
private static FoodMaker _instance;
public static FoodMaker Instance
{
get
{
return _instance;
}
}
public int xlimit = 21;
public int ylimit = 11;
public int xoffset = 7;
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);
GameObject food = Instantiate(foodPrefab);
food.GetComponent<Image>().sprite = foodSprites[index];
food.transform.SetParent(foodHolder, false);
int x = Random.Range(-xlimit + xoffset, xlimit);
int y = Random.Range(-ylimit, ylimit);
food.transform.localPosition = new Vector3(x * 30, y * 30, 0);
if (isReward)
{
GameObject reward = Instantiate(rewardPrefab);
reward.transform.SetParent(foodHolder, false);
x = Random.Range(-xlimit + xoffset, xlimit);
y = Random.Range(-ylimit, ylimit);
reward.transform.localPosition = new Vector3(x * 30, y * 30, 0);
}
}
}
代碼放置如下

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C# 實(shí)現(xiàn)Zookeeper分布式鎖的參考示例
Zookeeper分布式鎖的原理是巧妙的是使用了znode臨時(shí)節(jié)點(diǎn)的特點(diǎn)和監(jiān)聽(watcher)機(jī)制,監(jiān)聽機(jī)制很簡(jiǎn)單,就是我們可以給znode添加一個(gè)監(jiān)聽器,當(dāng)znode節(jié)點(diǎn)狀態(tài)發(fā)生改變時(shí)(如:數(shù)據(jù)內(nèi)容改變,節(jié)點(diǎn)被刪除),會(huì)通知到監(jiān)聽器。本文講解使用c#實(shí)現(xiàn)該功能2021-06-06
Unity3D實(shí)現(xiàn)控制攝像機(jī)移動(dòng)
這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)控制攝像機(jī)移動(dòng) ,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
C#中foreach原理以及模擬的實(shí)現(xiàn)
這篇文章主要介紹了C#中foreach原理以及模擬的實(shí)現(xiàn)方法,備有詳盡的注釋,便于深入理解C#原理,需要的朋友可以參考下2014-10-10
C#事件標(biāo)準(zhǔn)命名規(guī)則及說明(包括用作事件類型的委托命名)
這篇文章主要介紹了C#事件標(biāo)準(zhǔn)命名規(guī)則及說明(包括用作事件類型的委托命名),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
C#使用ZXing.Net實(shí)現(xiàn)識(shí)別二維碼和條碼
ZXing用Java實(shí)現(xiàn)的多種格式的一維二維條碼圖像處理庫,而ZXing.Net是其.Net版本的實(shí)現(xiàn),本文主要為大家詳細(xì)介紹了如何使用ZXing.Net實(shí)現(xiàn)識(shí)別二維碼和條碼,需要的可以參考下2024-01-01

