iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >使用unity怎么实现一个贪吃蛇游戏
  • 510
分享到

使用unity怎么实现一个贪吃蛇游戏

2023-06-14 09:06:43 510人浏览 八月长安
摘要

使用Unity怎么实现一个贪吃蛇游戏?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。具体内容如下using UnityEngine;using UnityEn

使用Unity怎么实现一个贪吃蛇游戏?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

具体内容如下

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) + ",分数" + PlayerPrefs.GetInt("lasts", 0);    bestText.text = "最好:长度" + PlayerPrefs.GetInt("bestl", 0) + ",分数" + 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/以及文件扩展名    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;                        //保存下来蛇头移动前的位置    gameObject.transform.localPosition = new Vector3(headPos.x + x, headPos.y + y, headPos.z); //蛇头向期望位置移动    if (bodyList.Count > 0)    {      //由于我们是双色蛇身,此方法弃用      //bodyList.Last().localPosition = headPos;                       //将蛇尾移动到蛇头移动前的位置      //bodyList.Insert(0, bodyList.Last());                         //将蛇尾在List中的位置更新到最前      //bodyList.RemoveAt(bodyList.Count - 1);                        //移除List最末尾的蛇尾引用      //由于我们是双色蛇身,使用此方法达到显示目的      for (int i = bodyList.Count - 2; i >= 0; i--)                      //从后往前开始移动蛇身      {        bodyList[i + 1].localPosition = bodyList[i].localPosition;             //每一个蛇身都移动到它前面一个节点的位置      }      bodyList[0].localPosition = headPos;                          //第一个蛇身移动到蛇头移动前的位置    }  }  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);    }  }}

看完上述内容,你们掌握使用unity怎么实现一个贪吃蛇游戏的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注编程网精选频道,感谢各位的阅读!

--结束END--

本文标题: 使用unity怎么实现一个贪吃蛇游戏

本文链接: https://www.lsjlt.com/news/269655.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 使用unity怎么实现一个贪吃蛇游戏
    使用unity怎么实现一个贪吃蛇游戏?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。具体内容如下using UnityEngine;using UnityEn...
    99+
    2023-06-14
  • unity实现简单的贪吃蛇游戏
    本文实例为大家分享了unity实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下 SatUIController代码 using UnityEngine; using Un...
    99+
    2024-04-02
  • 使用Java怎么实现一个贪吃蛇小游戏
    这篇文章将为大家详细讲解有关使用Java怎么实现一个贪吃蛇小游戏,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。 程序结构  程序结构图如图:2. 程序设计思路2.1 Data类作用:连接st...
    99+
    2023-06-14
  • JavaScript实现贪吃蛇游戏
    本文实例为大家分享了JavaScript实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 通过JavaScript,我们可以实现贪吃蛇游戏,具体功能如下: (1)通过按上下左右键来...
    99+
    2024-04-02
  • python怎么实现贪吃蛇游戏
    要实现贪吃蛇游戏,可以使用Python中的pygame库来进行游戏界面的绘制和键盘事件的监听。以下是一个简单的贪吃蛇游戏的示例代码:...
    99+
    2023-08-09
    python
  • 怎么用html5实现贪吃蛇游戏
    这篇文章主要讲解了“怎么用html5实现贪吃蛇游戏”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用html5实现贪吃蛇游戏”吧! ...
    99+
    2024-04-02
  • 怎么用C++实现贪吃蛇游戏
    这篇文章给大家分享的是有关怎么用C++实现贪吃蛇游戏的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。1976年,Gremlin平台推出了一款经典街机游戏Blockade。游戏中,两名玩家分别控制一个角色在屏幕上移动...
    99+
    2023-06-25
  • Java实现贪吃蛇游戏
    下面是一个简单的Java实现贪吃蛇游戏的示例代码:```javaimport javax.swing.*;import java.a...
    99+
    2023-08-09
    Java
  • QT实现贪吃蛇游戏
    为了熟悉QT的相关知识,我用了大约8个小时的时间用QT再次写了一遍贪吃蛇。 因为QT的机制和平时写的程序流程不同,所以程序中可能没有遵守代码规范。 运行效果: 程序内除了实现贪吃蛇...
    99+
    2024-04-02
  • 怎么使用python实现一个简单的贪吃蛇游戏
    本篇内容主要讲解“怎么使用python实现一个简单的贪吃蛇游戏”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么使用python实现一个简单的贪吃蛇游戏”吧!pygame 写的“贪吃蛇”小游戏:...
    99+
    2023-07-02
  • 怎么用JS实现贪吃蛇游戏
    本文小编为大家详细介绍“怎么用JS实现贪吃蛇游戏”,内容详细,步骤清晰,细节处理妥当,希望这篇“怎么用JS实现贪吃蛇游戏”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。效果图:完整代码如下:html:<!DO...
    99+
    2023-07-02
  • HTML5怎么实现贪吃蛇游戏
    本篇内容主要讲解“HTML5怎么实现贪吃蛇游戏”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“HTML5怎么实现贪吃蛇游戏”吧! &n...
    99+
    2024-04-02
  • pygame实现贪吃蛇游戏
    本文实例为大家分享了pygame实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 为了简化起见,游戏素材暂定为两张简单的图片(文中用的是30*30)。大家很方便就能制作。 背景也...
    99+
    2024-04-02
  • 用JS实现贪吃蛇游戏
    本文实例为大家分享了JS实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 效果图: 完整代码如下: html: <!DOCTYPE html> <html la...
    99+
    2024-04-02
  • python实现贪吃蛇游戏
    文章目录 1、效果2、实现过程3、代码 1、效果 2、实现过程 导入 Pygame 和 random 模块。初始化 Pygame。设置游戏界面大小、背景颜色和游戏标题。定义颜色常量。...
    99+
    2023-09-29
    python 游戏 pygame
  • java使用GUI实现贪吃蛇游戏
    本文实例为大家分享了java使用GUI实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 整个代码分为三部分 1.游戏开始界面2.data基本图片的添加3.面板,将小蛇画到面板上 这...
    99+
    2024-04-02
  • 怎么用Vue做个贪吃蛇游戏
    这篇文章主要介绍了怎么用Vue做个贪吃蛇游戏的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么用Vue做个贪吃蛇游戏文章都会有所收获,下面我们一起来看看吧。Vue.js写一个命令行贪吃蛇游戏安装npm ...
    99+
    2023-07-04
  • 怎么用PHP GUI做一个贪吃蛇游戏
    本篇内容介绍了“怎么用PHP GUI做一个贪吃蛇游戏”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!安装扩展官方手册的安装步骤是linux的:...
    99+
    2023-06-29
  • 用JS实现贪吃蛇小游戏
    本文实例为大家分享了JS实现贪吃蛇小游戏的具体代码,供大家参考,具体内容如下 效果图: 完整代码如下: HTML <!DOCTYPE html> <html la...
    99+
    2024-04-02
  • js怎么实现贪吃蛇小游戏
    这篇文章将为大家详细讲解有关js怎么实现贪吃蛇小游戏,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。示例代码<!DOCTYPE html> <h...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作