Unity制作贪吃蛇小游戏

  玩家通过“WASD”控制小蛇上下左右移动,蛇头撞倒食物,则食物被吃掉,蛇身体长一节,接着又出现食物,等待蛇来吃,如果蛇在移动中撞到墙或身体交叉蛇头撞倒自己身体游戏结束

  可通过游戏开始前对小蛇皮肤进行选择

  自由模式下蛇头可以穿过四周的墙

  使用本地持久化保存与读取的类——PlayerPrefs类对玩家游戏数据的存储

  PlayerPrefs类存储位置  传送门

  Unity圣典  传送门

  游戏项目已托管到Github上  传送门

游戏展示

对玩家的游戏数据记录

  游戏界面存储玩家最高分以及上一次游戏的分数

游戏换肤

  为玩家可以选择蓝色小蛇或黄色小蛇

游戏模式

  边界模式下蛇撞到边界判定游戏结束

  自由模式下蛇碰到边界时会从另一个边界线出来

(文字最下边有游戏脚本源代码)

  

实现过程

制作开始场景UI界面

 

  添加一个Canvas作为游戏开始场景并将Canvas下的Render Mode设置为Screen Space—Camera

  1. 1Screen Space-Overlay:这种模式层级视图中不需要任何的摄像机,且UI出现在所有摄像机的最前面。
  2. 2Screen Space-Camera:这种模式需要绑定一个UICamrea,它支持UI前面显示3D对象和粒子系统。
  3. 3World Space:这种模式,UI3d对象完全一样。

Canvas 三种渲染模式如下

(2D游戏常用Screen Space-Camera模式,3D游戏常用Screen Space-Overlay模式)

  

  Canvas Scaler(Script)个人比较喜欢设置UI Scale Mode设置成Scale With Screen Si   根据屏幕尺寸来调整UI的缩放值

  指定渲染摄像机

  添加游戏背景及控制面板

  使用UGUI制作游戏场景界面

  

  Bg(Image):制作游戏背景界面

ControlPanel(Panel):制作游戏选项区域

  Title(Text):制作游戏标题

  Go(Image):制作游戏开始图标

      添加Button控件,制作成按钮

      添加Outline外边框和Shadow阴影组件(逼真图片按钮)

  Text:"开始"文本

  添加十张Image作为游戏背景图片

  食物作为游戏背景太鲜明时,可以把食物的透明度调为150

  制作Text文字背景

  Mode下添加一个Toggle提供玩家对模式的选择

(给文字添加Outline给玩家一种朦胧感)

  

  边界模式下,蛇撞墙后判断游戏结束

  复制边界模式Toggle,修改文字为自由模式(自由模式下蛇撞墙后不会判定结束游戏)

  边界模式和自由模式玩家只能选择一个

  给Mode添加Toggle Group组件

  

  将Toggle Group组件绑定给Border和NoBorder

    

  is on :当前标签是否勾选

  同理添加小蛇皮肤属性

  将选择小蛇皮肤也设置成Toggle Group

  "黄色小蛇"和"自由模式" is on 去掉勾选

游戏场景UI界面

  ControlPanel下的按钮、文本控件

    Msg(Text):玩家选择游戏模式

    Score(Text):玩家当前得分

    Length(Text):当前蛇自身长度

    Home(Image):返回主页面按钮

    Pause(Image):停止游戏按钮

给游戏场景添加边界

  Bg下创建两个GameObject,设置(锚点)GameObject范围,添加Box Collider 2D作为游戏碰撞器

  给小蛇添加活动范围,添加一个Box Collider 2D碰撞器

  为了将活动范围标记出来,可以给碰撞其添加一个Image红色图片作为围墙

  修改一下碰撞器范围

 

制作贪吃蛇舌头并让其移动

  添加Image制作舌头,设置好舌头大小

  创建SnakeHead.cs脚本并绑定到蛇头部

  控制小蛇头部移动脚本

  1. void Move()
  2. {
  3. headPos = gameObject.transform.localPosition;
  4. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  5. }

  添加键盘按钮事件

  1. private void Update()
  2. {
  3. if (Input.GetKey(KeyCode.W))
  4. {
  5. x = ;y = step;
  6. }
  7. if (Input.GetKey(KeyCode.S))
  8. {
  9. x = ;y = -step;
  10. }
  11. if (Input.GetKey(KeyCode.A))
  12. {
  13. x = -step;y = ;
  14. }
  15. if (Input.GetKey(KeyCode.D))
  16. {
  17. x = step;y = ;
  18. }
  19. }

  

  初始时及改变方向时不断让小蛇向着一个方向移动

  1. private void Start()
  2. {
  3. //重复调用
  4. InvokeRepeating("Move",,velocity);
  5. x = step;y = ;
  6. }

  

  1. Invoke() 方法是 Unity3D 的一种委托机制
  2.  
  3. 如: Invoke("Test", ); 它的意思是: 秒之后调用 Test() 方法;
  4.  
  5. 使用 Invoke() 方法需要注意 3点:
  6.  
  7. :它应该在 脚本的生命周期里的(StartUpdateOnGUIFixedUpdateLateUpdate)中被调用;
  8.  
  9. Invoke(); 不能接受含有参数的方法;
  10.  
  11. :在 Time.ScaleTime = ; 时, Invoke() 无效,因为它不会被调用到
  12.  
  13. Invoke() 也支持重复调用:InvokeRepeating("Test", , );
  14.  
  15. 这个方法的意思是指: 秒后调用 Test() 方法,并且之后每隔 秒调用一次 Test() 方法
  16.  
  17. 还有两个重要的方法:
  18.  
  19. IsInvoking:用来判断某方法是否被延时,即将执行
  20. CancelInvoke:取消该脚本上的所有延时方法

Unity中Invoke 和 InvokeRepeating的区别

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SnakeHead : MonoBehaviour {
  6.  
  7. public float velocity=0.35f;
  8. public int step;
  9. private int x;
  10. private int y;
  11. private Vector3 headPos;
  12.  
  13. private void Start()
  14. {
  15. //重复调用
  16. InvokeRepeating("Move",,velocity);
  17. x = step;y = ;
  18. }
  19.  
  20. private void Update()
  21. {
  22. if (Input.GetKey(KeyCode.W))
  23. {
  24. x = ;y = step;
  25. }
  26. if (Input.GetKey(KeyCode.S))
  27. {
  28. x = ;y = -step;
  29. }
  30. if (Input.GetKey(KeyCode.A))
  31. {
  32. x = -step;y = ;
  33. }
  34. if (Input.GetKey(KeyCode.D))
  35. {
  36. x = step;y = ;
  37. }
  38. }
  39.  
  40. void Move()
  41. {
  42. headPos = gameObject.transform.localPosition;
  43. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  44. }
  45. }

SnakeHead.cs

  给小蛇头部添加转动时改变头部方向动画

  1. private void Update()
  2. {
  3. if (Input.GetKey(KeyCode.W))
  4. {
  5. gameObject.transform.localRotation = Quaternion.Euler(, , );
  6. x = ;y = step;
  7. }
  8. if (Input.GetKey(KeyCode.S))
  9. {
  10. gameObject.transform.localRotation = Quaternion.Euler(, , );
  11. x = ;y = -step;
  12. }
  13. if (Input.GetKey(KeyCode.A))
  14. {
  15. gameObject.transform.localRotation = Quaternion.Euler(, , );
  16. x = -step;y = ;
  17. }
  18. if (Input.GetKey(KeyCode.D))
  19. {
  20. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  21. x = step;y = ;
  22. }
  23. }

  发现小球向左走时还能向右走,向下走时还能向上走

  判断按键方法时候可以对方向进行一个判断

  1. private void Update()
  2. {
  3. if (Input.GetKey(KeyCode.W) && y!=-step)
  4. {
  5. gameObject.transform.localRotation = Quaternion.Euler(, , );
  6. x = ;y = step;
  7. }
  8. if (Input.GetKey(KeyCode.S) && y!=step )
  9. {
  10. gameObject.transform.localRotation = Quaternion.Euler(, , );
  11. x = ;y = -step;
  12. }
  13. if (Input.GetKey(KeyCode.A) && x!=step)
  14. {
  15. gameObject.transform.localRotation = Quaternion.Euler(, , );
  16. x = -step;y = ;
  17. }
  18. if (Input.GetKey(KeyCode.D) && x!=-step)
  19. {
  20. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  21. x = step;y = ;
  22. }
  23. }

  添加按下空格加快贪吃蛇向前移动速度

  1. if (Input.GetKeyDown(KeyCode.Space))
  2. {
  3. CancelInvoke();
  4. InvokeRepeating("Move",,velocity - 0.2f);
  5. }
  6.  
  7. if (Input.GetKeyUp(KeyCode.Space))
  8. {
  9. CancelInvoke();
  10. InvokeRepeating("Move", , velocity);
  11. }

  Unity圣典  传送门

  MonoBehaviour.CancelInvoke 取消调用

    MonoBehaviour.InvokeRepeating 重复调用

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SnakeHead : MonoBehaviour {
  6.  
  7. public float velocity=0.35f;
  8. public int step;
  9. private int x;
  10. private int y;
  11. private Vector3 headPos;
  12.  
  13. private void Start()
  14. {
  15. //重复调用
  16. InvokeRepeating("Move",,velocity);
  17. x = ;y = step;
  18. }
  19.  
  20. private void Update()
  21. {
  22. if (Input.GetKeyDown(KeyCode.Space))
  23. {
  24. CancelInvoke();
  25. InvokeRepeating("Move",,velocity - 0.2f);
  26. }
  27.  
  28. if (Input.GetKeyUp(KeyCode.Space))
  29. {
  30. CancelInvoke();
  31. InvokeRepeating("Move", , velocity);
  32. }
  33.  
  34. if (Input.GetKey(KeyCode.W) && y!=-step)
  35. {
  36. gameObject.transform.localRotation = Quaternion.Euler(, , );
  37. x = ;y = step;
  38. }
  39. if (Input.GetKey(KeyCode.S) && y!=step )
  40. {
  41. gameObject.transform.localRotation = Quaternion.Euler(, , );
  42. x = ;y = -step;
  43. }
  44. if (Input.GetKey(KeyCode.A) && x!=step)
  45. {
  46. gameObject.transform.localRotation = Quaternion.Euler(, , );
  47. x = -step;y = ;
  48. }
  49. if (Input.GetKey(KeyCode.D) && x!=-step)
  50. {
  51. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  52. x = step;y = ;
  53. }
  54. }
  55.  
  56. void Move()
  57. {
  58. headPos = gameObject.transform.localPosition;
  59. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  60. }
  61. }

SnakeHead.cs

第一个食物的随机生成

  对游戏边界范围的判定

  上边界与下边界

  经测试

  小蛇走11步碰到上边界,走10步碰到下边界

  小蛇走19步碰到右边界,走11步碰到左边界

  将食物和小蛇设置为预制体

  创建一个GameObject空物体对象挂在脚本和预制体

  游戏初始时获得游戏物体,并且生成食物

  1. private void Start()
  2. {
  3. foodHolder = GameObject.Find("FoodHolder").transform;
  4. MakeFood();
  5. }

  

  随机生成食物的位置

  1. public int xlimit = ;
  2. public int ylimit = ;
  3. //x轴活动空间不对称问题,对x轴的偏移值
  4. public int xoffset = ;
  5.  
  6. void MakeFood()
  7. {
  8. //生成x和y的随机值
  9. int x = Random.Range(-xlimit + xoffset,xlimit);
  10. int y = Random.Range(-ylimit,ylimit);
  11. //通过小蛇自身的步数长度来计算食物的活动空间
  12. food.transform.localPosition = new Vector3(x * , y * , );
  13. }

  随机生成食物的种类和位置

  1. void MakeFood()
  2. {
  3. int index = Random.Range(,foodSprites.Length);
  4. GameObject food = Instantiate(foodPrefab);
  5. food.GetComponent<Image>().sprite = foodSprites[index];
  6. food.transform.SetParent(foodHolder,false);
  7. int x = Random.Range(-xlimit + xoffset,xlimit);
  8. int y = Random.Range(-ylimit,ylimit);
  9. //通过小蛇自身的步数长度来计算食物的活动空间
  10. food.transform.localPosition = new Vector3(x * , y * , );
  11. }

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class FoodMaker : MonoBehaviour {
  7.  
  8. public int xlimit = ;
  9. public int ylimit = ;
  10. //x轴活动空间不对称问题,对x轴的偏移值
  11. public int xoffset = ;
  12. public GameObject foodPrefab;
  13. public Sprite[] foodSprites;
  14. private Transform foodHolder;
  15.  
  16. private void Start()
  17. {
  18. foodHolder = GameObject.Find("FoodHolder").transform;
  19. MakeFood();
  20. }
  21.  
  22. void MakeFood()
  23. {
  24. int index = Random.Range(,foodSprites.Length);
  25. GameObject food = Instantiate(foodPrefab);
  26. food.GetComponent<Image>().sprite = foodSprites[index];
  27. food.transform.SetParent(foodHolder,false);
  28. int x = Random.Range(-xlimit + xoffset,xlimit);
  29. int y = Random.Range(-ylimit,ylimit);
  30. //通过小蛇自身的步数长度来计算食物的活动空间
  31. food.transform.localPosition = new Vector3(x * , y * , );
  32. }
  33. }

FoodMaker.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SnakeHead : MonoBehaviour {
  6.  
  7. public float velocity=0.35f;
  8. public int step;
  9. private int x;
  10. private int y;
  11. private Vector3 headPos;
  12.  
  13. private void Start()
  14. {
  15. //重复调用
  16. InvokeRepeating("Move",,velocity);
  17. x = ;y = step;
  18. }
  19.  
  20. private void Update()
  21. {
  22. if (Input.GetKeyDown(KeyCode.Space))
  23. {
  24. CancelInvoke();
  25. InvokeRepeating("Move",,velocity - 0.2f);
  26. }
  27.  
  28. if (Input.GetKeyUp(KeyCode.Space))
  29. {
  30. CancelInvoke();
  31. InvokeRepeating("Move", , velocity);
  32. }
  33.  
  34. if (Input.GetKey(KeyCode.W) && y!=-step)
  35. {
  36. gameObject.transform.localRotation = Quaternion.Euler(, , );
  37. x = ;y = step;
  38. }
  39. if (Input.GetKey(KeyCode.S) && y!=step )
  40. {
  41. gameObject.transform.localRotation = Quaternion.Euler(, , );
  42. x = ;y = -step;
  43. }
  44. if (Input.GetKey(KeyCode.A) && x!=step)
  45. {
  46. gameObject.transform.localRotation = Quaternion.Euler(, , );
  47. x = -step;y = ;
  48. }
  49. if (Input.GetKey(KeyCode.D) && x!=-step)
  50. {
  51. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  52. x = step;y = ;
  53. }
  54. }
  55.  
  56. void Move()
  57. {
  58. headPos = gameObject.transform.localPosition;
  59. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  60. }
  61. }

SnakeHead.cs

吃掉食物(销毁)以及食物的随机生成

  给蛇头添加Box Collider 2D碰撞器,为避免蛇头未碰撞食物时碰撞器就碰撞到食物,可以设置碰撞器范围比蛇头小一圈

  勾选Is Trigger,当物体碰到食物及边界时,可以进入边界再判定游戏结束

  给蛇头添加Rigidbody 2D碰撞器,设置重力 Gravity Scale为0  (不然蛇头在开始游戏时就会不断往下掉)

  同理,给食物预设体Food添加Box Collider 2D碰撞器

  新创建一个Food标签作为标记

  将Food预设体标签设置为Food

  SnakeHead.cs中添加食物碰撞生成新食物方法

  1. private void OnTriggerEnter2D(Collider2D collision)
  2. {
  3. if (collision.gameObject.CompareTag("Food"))
  4. {
  5. Destroy(collision.gameObject);
  6. FoodMaker.Instance.MakeFood();
  7. }
  8. }

  FoodMaker.cs

  添加一个单例模式

  1. //单例模式
  2. private static FoodMaker _instance;
  3. //可以通过外部去调用方法修改_instance的值
  4. public static FoodMaker Instance
  5. {
  6. get
  7. {
  8. return _instance;
  9. }
  10. }
  11.  
  12. //初始化
  13. private void Awake()
  14. {
  15. _instance = this;
  16. }

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class FoodMaker : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static FoodMaker _instance;
  10. public static FoodMaker Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17. public int xlimit = ;
  18. public int ylimit = ;
  19. //x轴活动空间不对称问题,对x轴的偏移值
  20. public int xoffset = ;
  21. public GameObject foodPrefab;
  22. public Sprite[] foodSprites;
  23. private Transform foodHolder;
  24.  
  25. private void Awake()
  26. {
  27. _instance = this;
  28. }
  29.  
  30. private void Start()
  31. {
  32. foodHolder = GameObject.Find("FoodHolder").transform;
  33. MakeFood();
  34. }
  35.  
  36. public void MakeFood()
  37. {
  38. int index = Random.Range(,foodSprites.Length);
  39. GameObject food = Instantiate(foodPrefab);
  40. food.GetComponent<Image>().sprite = foodSprites[index];
  41. food.transform.SetParent(foodHolder,false);
  42. int x = Random.Range(-xlimit + xoffset,xlimit);
  43. int y = Random.Range(-ylimit,ylimit);
  44. //通过小蛇自身的步数长度来计算食物的活动空间
  45. food.transform.localPosition = new Vector3(x * , y * , );
  46. }
  47. }

FoodMaker.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SnakeHead : MonoBehaviour {
  6.  
  7. public float velocity=0.35f;
  8. public int step;
  9. private int x;
  10. private int y;
  11. private Vector3 headPos;
  12.  
  13. private void Start()
  14. {
  15. //重复调用
  16. InvokeRepeating("Move",,velocity);
  17. x = ;y = step;
  18. }
  19.  
  20. private void Update()
  21. {
  22. if (Input.GetKeyDown(KeyCode.Space))
  23. {
  24. CancelInvoke();
  25. InvokeRepeating("Move",,velocity - 0.2f);
  26. }
  27.  
  28. if (Input.GetKeyUp(KeyCode.Space))
  29. {
  30. CancelInvoke();
  31. InvokeRepeating("Move", , velocity);
  32. }
  33.  
  34. if (Input.GetKey(KeyCode.W) && y!=-step)
  35. {
  36. gameObject.transform.localRotation = Quaternion.Euler(, , );
  37. x = ;y = step;
  38. }
  39. if (Input.GetKey(KeyCode.S) && y!=step )
  40. {
  41. gameObject.transform.localRotation = Quaternion.Euler(, , );
  42. x = ;y = -step;
  43. }
  44. if (Input.GetKey(KeyCode.A) && x!=step)
  45. {
  46. gameObject.transform.localRotation = Quaternion.Euler(, , );
  47. x = -step;y = ;
  48. }
  49. if (Input.GetKey(KeyCode.D) && x!=-step)
  50. {
  51. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  52. x = step;y = ;
  53. }
  54. }
  55.  
  56. void Move()
  57. {
  58. headPos = gameObject.transform.localPosition;
  59. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  60. }
  61.  
  62. private void OnTriggerEnter2D(Collider2D collision)
  63. {
  64. if (collision.gameObject.CompareTag("Food"))
  65. {
  66. Destroy(collision.gameObject);
  67. FoodMaker.Instance.MakeFood();
  68. }
  69. }
  70.  
  71. }

SnakeHead.cs

蛇身吃掉食物的变长

  添加一个Image放置蛇身图片,添加Box Collider 2D碰撞器(碰撞器的范围不用太大,以免对食物产生不可描述的误操作)

  SnakeHead.cs脚本中生成蛇身

  创建一个集合,用来保存蛇身部分(两张图片不断轮流交换)

  1. public List<RectTransform> bodyList = new List<RectTransform>();
  2.  
  3. public GameObject bodyPrefab;
  4. public Sprite[] bodySprites = new Sprite[];

  生成蛇身体方法

  1. void Grow()
  2. {
  3. int index = (bodyList.Count % == ) ? : ;
  4. GameObject body = Instantiate(bodyPrefab);
  5. body.GetComponent<Image>().sprite = bodySprites[index];
  6. body.transform.SetParent(canvas,false);
  7. bodyList.Add(body.transform);
  8. }

蛇生体移动的方法

  创建一个链表,当蛇吃了食物后,将蛇身放置到链表中

  1. public List<Transform> bodyList = new List<Transform>();

  将图片放置到bodySprites中(两张),存放的都是bodyPrefab

  1. public GameObject bodyPrefab;
  2. public Sprite[] bodySprites = new Sprite[];
  3.  
  4. private void Awake()
  5. {
  6. canvas = GameObject.Find("Canvas").transform;
  7. }

  Unity中将预制体与贪吃蛇头部绑定一下

 

   蛇碰到食物后开始生成蛇身

  1. void Grow()
  2. {
  3. int index = (bodyList.Count % == ) ? : ;
  4. GameObject body = Instantiate(bodyPrefab,new Vector3(,,),Quaternion.identity);
  5. body.GetComponent<Image>().sprite = bodySprites[index];
  6. body.transform.SetParent(canvas, false);
  7. bodyList.Add(body.transform);
  8. }
  1. private void OnTriggerEnter2D(Collider2D collision)
  2. {
  3. if (collision.gameObject.CompareTag("Food"))
  4. {
  5. Destroy(collision.gameObject);
  6. Grow();
  7. FoodMaker.Instance.MakeFood();
  8. }
  9. }

  

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class FoodMaker : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static FoodMaker _instance;
  10. public static FoodMaker Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17. public int xlimit = ;
  18. public int ylimit = ;
  19. //x轴活动空间不对称问题,对x轴的偏移值
  20. public int xoffset = ;
  21. public GameObject foodPrefab;
  22. public Sprite[] foodSprites;
  23. private Transform foodHolder;
  24.  
  25. private void Awake()
  26. {
  27. _instance = this;
  28. }
  29.  
  30. private void Start()
  31. {
  32. foodHolder = GameObject.Find("FoodHolder").transform;
  33. MakeFood();
  34. }
  35.  
  36. public void MakeFood()
  37. {
  38. int index = Random.Range(,foodSprites.Length);
  39. GameObject food = Instantiate(foodPrefab);
  40. food.GetComponent<Image>().sprite = foodSprites[index];
  41. food.transform.SetParent(foodHolder,false);
  42. int x = Random.Range(-xlimit + xoffset,xlimit);
  43. int y = Random.Range(-ylimit,ylimit);
  44. food.transform.localPosition = new Vector3(x * , y * , );
  45. //food.transform.localPosition = new Vector3( x, y, 0);
  46. }
  47. }

FoodMaker.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6.  
  7. public class SnakeHead : MonoBehaviour {
  8.  
  9. public List<Transform> bodyList = new List<Transform>();
  10. public float velocity=0.35f;
  11. public int step;
  12. private int x;
  13. private int y;
  14. private Vector3 headPos;
  15. private Transform canvas;
  16.  
  17. public GameObject bodyPrefab;
  18. public Sprite[] bodySprites = new Sprite[];
  19.  
  20. private void Awake()
  21. {
  22. canvas = GameObject.Find("Canvas").transform;
  23. }
  24.  
  25. private void Start()
  26. {
  27. //重复调用
  28. InvokeRepeating("Move",,velocity);
  29. x = ;y = step;
  30. }
  31.  
  32. private void Update()
  33. {
  34. if (Input.GetKeyDown(KeyCode.Space))
  35. {
  36. CancelInvoke();
  37. InvokeRepeating("Move",,velocity - 0.3f);
  38. }
  39.  
  40. if (Input.GetKeyUp(KeyCode.Space))
  41. {
  42. CancelInvoke();
  43. InvokeRepeating("Move", , velocity);
  44. }
  45.  
  46. if (Input.GetKey(KeyCode.W) && y!=-step)
  47. {
  48. gameObject.transform.localRotation = Quaternion.Euler(, , );
  49. x = ;y = step;
  50. }
  51. if (Input.GetKey(KeyCode.S) && y!=step )
  52. {
  53. gameObject.transform.localRotation = Quaternion.Euler(, , );
  54. x = ;y = -step;
  55. }
  56. if (Input.GetKey(KeyCode.A) && x!=step)
  57. {
  58. gameObject.transform.localRotation = Quaternion.Euler(, , );
  59. x = -step;y = ;
  60. }
  61. if (Input.GetKey(KeyCode.D) && x!=-step)
  62. {
  63. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  64. x = step;y = ;
  65. }
  66. }
  67.  
  68. void Move()
  69. {
  70. //保存下来蛇头移动前的位置
  71. headPos = gameObject.transform.localPosition;
  72. //蛇头向期望位置移动
  73. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  74. if (bodyList.Count > )
  75. {
  76. //由于是双色蛇身,此方法弃用
  77. //将蛇尾移动到蛇头移动前的位置
  78. // bodyList.Last().localPosition = headPos;
  79. //将蛇尾在List中的位置跟新到最前
  80. // bodyList.Insert(0, bodyList.Last());
  81. //溢出List最末尾的蛇尾引用
  82. // bodyList.RemoveAt(bodyList.Count - 1);
  83.  
  84. //从后面开始移动蛇身
  85. for(int i =bodyList.Count-;i>= ;i--)
  86. {
  87. //每一个蛇身都移动到它前面一个
  88. bodyList[i + ].localPosition = bodyList[i].localPosition;
  89. }
  90. //第一个蛇身移动到蛇头移动前的位置
  91. bodyList[].localPosition = headPos;
  92.  
  93. }
  94. }
  95.  
  96. void Grow()
  97. {
  98. int index = (bodyList.Count % == ) ? : ;
  99. GameObject body = Instantiate(bodyPrefab,new Vector3(,,),Quaternion.identity);
  100. body.GetComponent<Image>().sprite = bodySprites[index];
  101. body.transform.SetParent(canvas, false);
  102. bodyList.Add(body.transform);
  103. }
  104.  
  105. private void OnTriggerEnter2D(Collider2D collision)
  106. {
  107. if (collision.gameObject.CompareTag("Food"))
  108. {
  109. Destroy(collision.gameObject);
  110. Grow();
  111. FoodMaker.Instance.MakeFood();
  112. }
  113. }
  114.  
  115. }

SnakeHead.cs

游戏的自由模式

  当小蛇撞到上边界时再往下走一步后从下边界出现

  当小蛇撞到下边界时再往上走一步后从上边界出现

  当小蛇撞到上边界时再往下走一步后从下边界出现

  当小蛇撞到上边界时再往下走一步后从下边界出现

  1. switch(collision.gameObject.name)
  2. {
  3. case "Up":
  4. transform.localPosition = new Vector3(transform.localPosition.x,-transform.localPosition.y+,transform.localPosition.z);
  5. break;
  6. case "Down":
  7. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y-, transform.localPosition.z);
  8. break;
  9. case "Left":
  10. transform.localPosition = new Vector3(-transform.localPosition.x+,transform.localPosition.y , transform.localPosition.z);
  11. break;
  12. case "Right":
  13. transform.localPosition = new Vector3(-transform.localPosition.x+, transform.localPosition.y, transform.localPosition.z);
  14. break;
  15. }

奖励目标的生成

  添加一个Reward(Image)作为奖励目标背景图片

  调整奖励背景图片和食物大小保持一样,并添加Box Collider 2D组件

  

  将Resward作为预制体

  FoodMaker.cs上绑定rewardPrefabs预制体

  1. public GameObject rewardPrefab;

  

  判断是否生成道具

  1. public void MakeFood(bool isReward)
  2. {
  3. int index = Random.Range(,foodSprites.Length);
  4. GameObject food = Instantiate(foodPrefab);
  5. food.GetComponent<Image>().sprite = foodSprites[index];
  6. food.transform.SetParent(foodHolder,false);
  7. int x = Random.Range(-xlimit + xoffset,xlimit);
  8. int y = Random.Range(-ylimit,ylimit);
  9. food.transform.localPosition = new Vector3(x * , y * , );
  10. //food.transform.localPosition = new Vector3( x, y, 0);
  11. if(isReward==true)
  12. {
  13. GameObject reward = Instantiate(rewardPrefab);
  14. reward.transform.SetParent(foodHolder, false);
  15. x = Random.Range(-xlimit + xoffset, xlimit);
  16. y = Random.Range(-ylimit, ylimit);
  17. reward.transform.localPosition = new Vector3(x * , y * , );
  18. }
  19. }

  当蛇吃到食物后,有百分之20的机率生成道具

  1. if (collision.gameObject.CompareTag("Food"))
  2. {
  3. Destroy(collision.gameObject);
  4. Grow();
  5. if (Random.Range(,)<)
  6. {
  7. FoodMaker.Instance.MakeFood(true);
  8. }
  9. else
  10. {
  11. FoodMaker.Instance.MakeFood(false);
  12. }
  13. }

  当蛇吃到道具时,道具销毁

  1. else if(collision.gameObject.CompareTag("Reward"))
  2. {
  3. Destroy(collision.gameObject);
  4. Grow();
  5. }

  

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6.  
  7. public class SnakeHead : MonoBehaviour {
  8.  
  9. public List<Transform> bodyList = new List<Transform>();
  10. public float velocity=0.35f;
  11. public int step;
  12. private int x;
  13. private int y;
  14. private Vector3 headPos;
  15. private Transform canvas;
  16.  
  17. public GameObject bodyPrefab;
  18. public Sprite[] bodySprites = new Sprite[];
  19.  
  20. private void Awake()
  21. {
  22. canvas = GameObject.Find("Canvas").transform;
  23. }
  24.  
  25. private void Start()
  26. {
  27. //重复调用
  28. InvokeRepeating("Move",,velocity);
  29. x = ;y = step;
  30. }
  31.  
  32. private void Update()
  33. {
  34. if (Input.GetKeyDown(KeyCode.Space))
  35. {
  36. CancelInvoke();
  37. InvokeRepeating("Move",,velocity - 0.3f);
  38. }
  39.  
  40. if (Input.GetKeyUp(KeyCode.Space))
  41. {
  42. CancelInvoke();
  43. InvokeRepeating("Move", , velocity);
  44. }
  45.  
  46. if (Input.GetKey(KeyCode.W) && y!=-step)
  47. {
  48. gameObject.transform.localRotation = Quaternion.Euler(, , );
  49. x = ;y = step;
  50. }
  51. if (Input.GetKey(KeyCode.S) && y!=step )
  52. {
  53. gameObject.transform.localRotation = Quaternion.Euler(, , );
  54. x = ;y = -step;
  55. }
  56. if (Input.GetKey(KeyCode.A) && x!=step)
  57. {
  58. gameObject.transform.localRotation = Quaternion.Euler(, , );
  59. x = -step;y = ;
  60. }
  61. if (Input.GetKey(KeyCode.D) && x!=-step)
  62. {
  63. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  64. x = step;y = ;
  65. }
  66. }
  67.  
  68. void Move()
  69. {
  70. //保存下来蛇头移动前的位置
  71. headPos = gameObject.transform.localPosition;
  72. //蛇头向期望位置移动
  73. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  74. if (bodyList.Count > )
  75. {
  76. //由于是双色蛇身,此方法弃用
  77. //将蛇尾移动到蛇头移动前的位置
  78. // bodyList.Last().localPosition = headPos;
  79. //将蛇尾在List中的位置跟新到最前
  80. // bodyList.Insert(0, bodyList.Last());
  81. //溢出List最末尾的蛇尾引用
  82. // bodyList.RemoveAt(bodyList.Count - 1);
  83.  
  84. //从后面开始移动蛇身
  85. for(int i =bodyList.Count-;i>= ;i--)
  86. {
  87. //每一个蛇身都移动到它前面一个
  88. bodyList[i + ].localPosition = bodyList[i].localPosition;
  89. }
  90. //第一个蛇身移动到蛇头移动前的位置
  91. bodyList[].localPosition = headPos;
  92.  
  93. }
  94. }
  95.  
  96. void Grow()
  97. {
  98. int index = (bodyList.Count % == ) ? : ;
  99. GameObject body = Instantiate(bodyPrefab,new Vector3(,,),Quaternion.identity);
  100. body.GetComponent<Image>().sprite = bodySprites[index];
  101. body.transform.SetParent(canvas, false);
  102. bodyList.Add(body.transform);
  103. }
  104.  
  105. private void OnTriggerEnter2D(Collider2D collision)
  106. {
  107. if (collision.gameObject.CompareTag("Food"))
  108. {
  109. Destroy(collision.gameObject);
  110. Grow();
  111. if (Random.Range(,)<)
  112. {
  113. FoodMaker.Instance.MakeFood(true);
  114. }
  115. else
  116. {
  117. FoodMaker.Instance.MakeFood(false);
  118. }
  119. }
  120. else if(collision.gameObject.CompareTag("Reward"))
  121. {
  122. Destroy(collision.gameObject);
  123. Grow();
  124. }
  125. else if(collision.gameObject.CompareTag("Body"))
  126. {
  127. Debug.Log("Die");
  128. }
  129. else
  130. {
  131. switch(collision.gameObject.name)
  132. {
  133. case "Up":
  134. transform.localPosition = new Vector3(transform.localPosition.x,-transform.localPosition.y+,transform.localPosition.z);
  135. break;
  136. case "Down":
  137. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y-, transform.localPosition.z);
  138. break;
  139. case "Left":
  140. transform.localPosition = new Vector3(-transform.localPosition.x+,transform.localPosition.y , transform.localPosition.z);
  141. break;
  142. case "Right":
  143. transform.localPosition = new Vector3(-transform.localPosition.x+, transform.localPosition.y, transform.localPosition.z);
  144. break;
  145. }
  146. }
  147. }
  148.  
  149. }

SnakeHead.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class FoodMaker : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static FoodMaker _instance;
  10. public static FoodMaker Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17. public int xlimit = ;
  18. public int ylimit = ;
  19. //x轴活动空间不对称问题,对x轴的偏移值
  20. public int xoffset = ;
  21. public GameObject foodPrefab;
  22. public GameObject rewardPrefab;
  23. public Sprite[] foodSprites;
  24. private Transform foodHolder;
  25.  
  26. private void Awake()
  27. {
  28. _instance = this;
  29. }
  30.  
  31. private void Start()
  32. {
  33. foodHolder = GameObject.Find("FoodHolder").transform;
  34. MakeFood(false);
  35. }
  36.  
  37. public void MakeFood(bool isReward)
  38. {
  39. int index = Random.Range(,foodSprites.Length);
  40. GameObject food = Instantiate(foodPrefab);
  41. food.GetComponent<Image>().sprite = foodSprites[index];
  42. food.transform.SetParent(foodHolder,false);
  43. int x = Random.Range(-xlimit + xoffset,xlimit);
  44. int y = Random.Range(-ylimit,ylimit);
  45. food.transform.localPosition = new Vector3(x * , y * , );
  46. //food.transform.localPosition = new Vector3( x, y, 0);
  47. if(isReward==true)
  48. {
  49. GameObject reward = Instantiate(rewardPrefab);
  50. reward.transform.SetParent(foodHolder, false);
  51. x = Random.Range(-xlimit + xoffset, xlimit);
  52. y = Random.Range(-ylimit, ylimit);
  53. reward.transform.localPosition = new Vector3(x * , y * , );
  54. }
  55. }
  56. }

FoodMaker.cs

分数与长度与游戏背景切换

  新建一个脚本MainUIController.cs来存储蛇的分数与长度

  分数的单例模式

  1. //单例模式
  2. private static MainUIController _instance;
  3. public static MainUIController Instance
  4. {
  5. get
  6. {
  7. return _instance;
  8. }
  9. }

  

  游戏加分方法  默认吃到一个食物加5分1个长度  获得道具加分会更高

  1. public void UpdateUI(int s = ,int l = )
  2. {
  3. score += s;
  4. length += l;
  5. scoreText.text ="得分:\n"+score;
  6. lengthText.text = "长度\n" + length;
  7. }

  当蛇吃到食物或道具时调用UpdateUI()方法

  1. if (collision.gameObject.CompareTag("Food"))
  2. {
  3. Destroy(collision.gameObject);
  4. MainUIController.Instance.UpdateUI();
  5. Grow();
  6. if (Random.Range(,)<)
  7. {
  8. FoodMaker.Instance.MakeFood(true);
  9. }
  10. else
  11. {
  12. FoodMaker.Instance.MakeFood(false);
  13. }
  14. }
  15. else if(collision.gameObject.CompareTag("Reward"))
  16. {
  17. Destroy(collision.gameObject);
  18. MainUIController.Instance.UpdateUI(Random.Range(,)*);
  19. Grow();
  20. }

  当分数达到一定数值时能进行游戏背景变色

  1. private void Update()
  2. {
  3. switch (score / )
  4. {
  5. case :
  6. ColorUtility.TryParseHtmlString("#CCEEFFFF",out tempColor);
  7. bgImage.color=tempColor;
  8. msgText.text = "阶段" + ;
  9. break;
  10. case :
  11. ColorUtility.TryParseHtmlString("#CCEEFFFF", out tempColor);
  12. bgImage.color = tempColor;
  13. msgText.text = "阶段" + ;
  14. break;
  15. case :
  16. ColorUtility.TryParseHtmlString("#CCFFDBFF", out tempColor);
  17. bgImage.color = tempColor;
  18. msgText.text = "阶段" + ;
  19. break;
  20. case :
  21. ColorUtility.TryParseHtmlString("#EBFFCCFF", out tempColor);
  22. bgImage.color = tempColor;
  23. msgText.text = "阶段" + ;
  24. break;
  25. case :
  26. ColorUtility.TryParseHtmlString("#FFDACCFF", out tempColor);
  27. bgImage.color = tempColor;
  28. msgText.text = "阶段 x";
  29. break;
  30. }
  31. }

  将脚本放在Script游戏物体上,并绑定分数版、背景等

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6.  
  7. public class SnakeHead : MonoBehaviour {
  8.  
  9. public List<Transform> bodyList = new List<Transform>();
  10. public float velocity=0.35f;
  11. public int step;
  12. private int x;
  13. private int y;
  14. private Vector3 headPos;
  15. private Transform canvas;
  16.  
  17. public GameObject bodyPrefab;
  18. public Sprite[] bodySprites = new Sprite[];
  19.  
  20. private void Awake()
  21. {
  22. canvas = GameObject.Find("Canvas").transform;
  23. }
  24.  
  25. private void Start()
  26. {
  27. //重复调用
  28. InvokeRepeating("Move",,velocity);
  29. x = ;y = step;
  30. }
  31.  
  32. private void Update()
  33. {
  34. if (Input.GetKeyDown(KeyCode.Space))
  35. {
  36. CancelInvoke();
  37. InvokeRepeating("Move",,velocity - 0.3f);
  38. }
  39.  
  40. if (Input.GetKeyUp(KeyCode.Space))
  41. {
  42. CancelInvoke();
  43. InvokeRepeating("Move", , velocity);
  44. }
  45.  
  46. if (Input.GetKey(KeyCode.W) && y!=-step)
  47. {
  48. gameObject.transform.localRotation = Quaternion.Euler(, , );
  49. x = ;y = step;
  50. }
  51. if (Input.GetKey(KeyCode.S) && y!=step )
  52. {
  53. gameObject.transform.localRotation = Quaternion.Euler(, , );
  54. x = ;y = -step;
  55. }
  56. if (Input.GetKey(KeyCode.A) && x!=step)
  57. {
  58. gameObject.transform.localRotation = Quaternion.Euler(, , );
  59. x = -step;y = ;
  60. }
  61. if (Input.GetKey(KeyCode.D) && x!=-step)
  62. {
  63. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  64. x = step;y = ;
  65. }
  66. }
  67.  
  68. void Move()
  69. {
  70. //保存下来蛇头移动前的位置
  71. headPos = gameObject.transform.localPosition;
  72. //蛇头向期望位置移动
  73. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  74. if (bodyList.Count > )
  75. {
  76. //由于是双色蛇身,此方法弃用
  77. //将蛇尾移动到蛇头移动前的位置
  78. // bodyList.Last().localPosition = headPos;
  79. //将蛇尾在List中的位置跟新到最前
  80. // bodyList.Insert(0, bodyList.Last());
  81. //溢出List最末尾的蛇尾引用
  82. // bodyList.RemoveAt(bodyList.Count - 1);
  83.  
  84. //从后面开始移动蛇身
  85. for(int i =bodyList.Count-;i>= ;i--)
  86. {
  87. //每一个蛇身都移动到它前面一个
  88. bodyList[i + ].localPosition = bodyList[i].localPosition;
  89. }
  90. //第一个蛇身移动到蛇头移动前的位置
  91. bodyList[].localPosition = headPos;
  92.  
  93. }
  94. }
  95.  
  96. void Grow()
  97. {
  98. int index = (bodyList.Count % == ) ? : ;
  99. GameObject body = Instantiate(bodyPrefab,new Vector3(,,),Quaternion.identity);
  100. body.GetComponent<Image>().sprite = bodySprites[index];
  101. body.transform.SetParent(canvas, false);
  102. bodyList.Add(body.transform);
  103. }
  104.  
  105. private void OnTriggerEnter2D(Collider2D collision)
  106. {
  107. if (collision.gameObject.CompareTag("Food"))
  108. {
  109. Destroy(collision.gameObject);
  110. MainUIController.Instance.UpdateUI();
  111. Grow();
  112. if (Random.Range(,)<)
  113. {
  114. FoodMaker.Instance.MakeFood(true);
  115. }
  116. else
  117. {
  118. FoodMaker.Instance.MakeFood(false);
  119. }
  120. }
  121. else if(collision.gameObject.CompareTag("Reward"))
  122. {
  123. Destroy(collision.gameObject);
  124. MainUIController.Instance.UpdateUI(Random.Range(,)*);
  125. Grow();
  126. }
  127. else if(collision.gameObject.CompareTag("Body"))
  128. {
  129. Debug.Log("Die");
  130. }
  131. else
  132. {
  133. switch(collision.gameObject.name)
  134. {
  135. case "Up":
  136. transform.localPosition = new Vector3(transform.localPosition.x,-transform.localPosition.y+,transform.localPosition.z);
  137. break;
  138. case "Down":
  139. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y-, transform.localPosition.z);
  140. break;
  141. case "Left":
  142. transform.localPosition = new Vector3(-transform.localPosition.x+,transform.localPosition.y , transform.localPosition.z);
  143. break;
  144. case "Right":
  145. transform.localPosition = new Vector3(-transform.localPosition.x+, transform.localPosition.y, transform.localPosition.z);
  146. break;
  147. }
  148. }
  149. }
  150.  
  151. }

SnakeHead.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class FoodMaker : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static FoodMaker _instance;
  10. public static FoodMaker Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17. public int xlimit = ;
  18. public int ylimit = ;
  19. //x轴活动空间不对称问题,对x轴的偏移值
  20. public int xoffset = ;
  21. public GameObject foodPrefab;
  22. public GameObject rewardPrefab;
  23. public Sprite[] foodSprites;
  24. private Transform foodHolder;
  25.  
  26. private void Awake()
  27. {
  28. _instance = this;
  29. }
  30.  
  31. private void Start()
  32. {
  33. foodHolder = GameObject.Find("FoodHolder").transform;
  34. MakeFood(false);
  35. }
  36.  
  37. public void MakeFood(bool isReward)
  38. {
  39. int index = Random.Range(,foodSprites.Length);
  40. GameObject food = Instantiate(foodPrefab);
  41. food.GetComponent<Image>().sprite = foodSprites[index];
  42. food.transform.SetParent(foodHolder,false);
  43. int x = Random.Range(-xlimit + xoffset,xlimit);
  44. int y = Random.Range(-ylimit,ylimit);
  45. food.transform.localPosition = new Vector3(x * , y * , );
  46. //food.transform.localPosition = new Vector3( x, y, 0);
  47. if(isReward==true)
  48. {
  49. GameObject reward = Instantiate(rewardPrefab);
  50. reward.transform.SetParent(foodHolder, false);
  51. x = Random.Range(-xlimit + xoffset, xlimit);
  52. y = Random.Range(-ylimit, ylimit);
  53. reward.transform.localPosition = new Vector3(x * , y * , );
  54. }
  55. }
  56. }

FoodMaker.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class MainUIController : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static MainUIController _instance;
  10. public static MainUIController Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17.  
  18. public int score = ;
  19. public int length = ;
  20. public Text msgText;
  21. public Text scoreText;
  22. public Text lengthText;
  23. public Image bgImage;
  24. private Color tempColor;
  25.  
  26. void Awake()
  27. {
  28. _instance = this;
  29. }
  30.  
  31. private void Update()
  32. {
  33. switch (score / )
  34. {
  35. case :
  36. ColorUtility.TryParseHtmlString("#CCEEFFFF",out tempColor);
  37. bgImage.color=tempColor;
  38. msgText.text = "阶段" + ;
  39. break;
  40. case :
  41. ColorUtility.TryParseHtmlString("#CCEEFFFF", out tempColor);
  42. bgImage.color = tempColor;
  43. msgText.text = "阶段" + ;
  44. break;
  45. case :
  46. ColorUtility.TryParseHtmlString("#CCFFDBFF", out tempColor);
  47. bgImage.color = tempColor;
  48. msgText.text = "阶段" + ;
  49. break;
  50. case :
  51. ColorUtility.TryParseHtmlString("#EBFFCCFF", out tempColor);
  52. bgImage.color = tempColor;
  53. msgText.text = "阶段" + ;
  54. break;
  55. case :
  56. ColorUtility.TryParseHtmlString("#FFDACCFF", out tempColor);
  57. bgImage.color = tempColor;
  58. msgText.text = "阶段 x";
  59. break;
  60. }
  61. }
  62.  
  63. public void UpdateUI(int s = ,int l = )
  64. {
  65. score += s;
  66. length += l;
  67. scoreText.text ="得分:\n"+score;
  68. lengthText.text = "长度\n" + length;
  69. }
  70.  
  71. }

MainUIController.cs

暂停与返回按钮

  对按钮进行引用以及添加一个图片Sprite[]

  1. public Button pauseButton;
  2. public Sprite[] pauseSprites;

  设置一个变量记录游戏状态

  1. private bool isPause = false ;

  点击按钮时候对游戏状态取反

  1. public void Pause()
  2. {
  3. isPause = !isPause;
  4. if(isPause)
  5. {
  6. Time.timeScale = ;
  7. pauseButton.GetComponent<Image>().sprite = pauseSprites[];
  8. }
  9. else
  10. {
  11. Time.timeScale = ;
  12. pauseButton.GetComponent<Image>().sprite = pauseSprites[];
  13. }
  14. }

  Time.timeScale  传送门

  Script中对图片、按钮进行绑定

  

  

  在onclick()

  解决按键冲突

  按键控制器Edit->Project Settings-> Input

    

  

  1. private void Update()
  2. {
  3. if (Input.GetKeyDown(KeyCode.Space)&&MainUIController.Instance.isPause==false)
  4. {
  5. CancelInvoke();
  6. InvokeRepeating("Move",,velocity - 0.3f);
  7. }
  8.  
  9. if (Input.GetKeyUp(KeyCode.Space) && MainUIController.Instance.isPause == false)
  10. {
  11. CancelInvoke();
  12. InvokeRepeating("Move", , velocity);
  13. }
  14.  
  15. if (Input.GetKey(KeyCode.W) && y!=-step && MainUIController.Instance.isPause == false)
  16. {
  17. gameObject.transform.localRotation = Quaternion.Euler(, , );
  18. x = ;y = step;
  19. }
  20. if (Input.GetKey(KeyCode.S) && y!=step && MainUIController.Instance.isPause == false)
  21. {
  22. gameObject.transform.localRotation = Quaternion.Euler(, , );
  23. x = ;y = -step;
  24. }
  25. if (Input.GetKey(KeyCode.A) && x!=step && MainUIController.Instance.isPause == false)
  26. {
  27. gameObject.transform.localRotation = Quaternion.Euler(, , );
  28. x = -step;y = ;
  29. }
  30. if (Input.GetKey(KeyCode.D) && x!=-step && MainUIController.Instance.isPause == false)
  31. {
  32. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  33. x = step;y = ;
  34. }
  35. }

Update()中对键盘按下事件进行处理

 

   接下来实现返回按钮

  1. public void Home()
  2. {
  3. UnityEngine.SceneManagement.SceneManager.LoadScene();
  4. }

  Home按钮上添加点击事件

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6.  
  7. public class SnakeHead : MonoBehaviour {
  8.  
  9. public List<Transform> bodyList = new List<Transform>();
  10. public float velocity=0.35f;
  11. public int step;
  12. private int x;
  13. private int y;
  14. private Vector3 headPos;
  15. private Transform canvas;
  16.  
  17. public GameObject bodyPrefab;
  18. public Sprite[] bodySprites = new Sprite[];
  19.  
  20. private void Awake()
  21. {
  22. canvas = GameObject.Find("Canvas").transform;
  23. }
  24.  
  25. private void Start()
  26. {
  27. //重复调用
  28. InvokeRepeating("Move",,velocity);
  29. x = ;y = step;
  30. }
  31.  
  32. private void Update()
  33. {
  34. if (Input.GetKeyDown(KeyCode.Space)&&MainUIController.Instance.isPause==false)
  35. {
  36. CancelInvoke();
  37. InvokeRepeating("Move",,velocity - 0.3f);
  38. }
  39.  
  40. if (Input.GetKeyUp(KeyCode.Space) && MainUIController.Instance.isPause == false)
  41. {
  42. CancelInvoke();
  43. InvokeRepeating("Move", , velocity);
  44. }
  45.  
  46. if (Input.GetKey(KeyCode.W) && y!=-step && MainUIController.Instance.isPause == false)
  47. {
  48. gameObject.transform.localRotation = Quaternion.Euler(, , );
  49. x = ;y = step;
  50. }
  51. if (Input.GetKey(KeyCode.S) && y!=step && MainUIController.Instance.isPause == false)
  52. {
  53. gameObject.transform.localRotation = Quaternion.Euler(, , );
  54. x = ;y = -step;
  55. }
  56. if (Input.GetKey(KeyCode.A) && x!=step && MainUIController.Instance.isPause == false)
  57. {
  58. gameObject.transform.localRotation = Quaternion.Euler(, , );
  59. x = -step;y = ;
  60. }
  61. if (Input.GetKey(KeyCode.D) && x!=-step && MainUIController.Instance.isPause == false)
  62. {
  63. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  64. x = step;y = ;
  65. }
  66. }
  67.  
  68. void Move()
  69. {
  70. //保存下来蛇头移动前的位置
  71. headPos = gameObject.transform.localPosition;
  72. //蛇头向期望位置移动
  73. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  74. if (bodyList.Count > )
  75. {
  76. //由于是双色蛇身,此方法弃用
  77. //将蛇尾移动到蛇头移动前的位置
  78. // bodyList.Last().localPosition = headPos;
  79. //将蛇尾在List中的位置跟新到最前
  80. // bodyList.Insert(0, bodyList.Last());
  81. //溢出List最末尾的蛇尾引用
  82. // bodyList.RemoveAt(bodyList.Count - 1);
  83.  
  84. //从后面开始移动蛇身
  85. for(int i =bodyList.Count-;i>= ;i--)
  86. {
  87. //每一个蛇身都移动到它前面一个
  88. bodyList[i + ].localPosition = bodyList[i].localPosition;
  89. }
  90. //第一个蛇身移动到蛇头移动前的位置
  91. bodyList[].localPosition = headPos;
  92.  
  93. }
  94. }
  95.  
  96. void Grow()
  97. {
  98. int index = (bodyList.Count % == ) ? : ;
  99. GameObject body = Instantiate(bodyPrefab,new Vector3(,,),Quaternion.identity);
  100. body.GetComponent<Image>().sprite = bodySprites[index];
  101. body.transform.SetParent(canvas, false);
  102. bodyList.Add(body.transform);
  103. }
  104.  
  105. private void OnTriggerEnter2D(Collider2D collision)
  106. {
  107. if (collision.gameObject.CompareTag("Food"))
  108. {
  109. Destroy(collision.gameObject);
  110. MainUIController.Instance.UpdateUI();
  111. Grow();
  112. if (Random.Range(,)<)
  113. {
  114. FoodMaker.Instance.MakeFood(true);
  115. }
  116. else
  117. {
  118. FoodMaker.Instance.MakeFood(false);
  119. }
  120. }
  121. else if(collision.gameObject.CompareTag("Reward"))
  122. {
  123. Destroy(collision.gameObject);
  124. MainUIController.Instance.UpdateUI(Random.Range(,)*);
  125. Grow();
  126. }
  127. else if(collision.gameObject.CompareTag("Body"))
  128. {
  129. Debug.Log("Die");
  130. }
  131. else
  132. {
  133. switch(collision.gameObject.name)
  134. {
  135. case "Up":
  136. transform.localPosition = new Vector3(transform.localPosition.x,-transform.localPosition.y+,transform.localPosition.z);
  137. break;
  138. case "Down":
  139. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y-, transform.localPosition.z);
  140. break;
  141. case "Left":
  142. transform.localPosition = new Vector3(-transform.localPosition.x+,transform.localPosition.y , transform.localPosition.z);
  143. break;
  144. case "Right":
  145. transform.localPosition = new Vector3(-transform.localPosition.x+, transform.localPosition.y, transform.localPosition.z);
  146. break;
  147. }
  148. }
  149. }
  150.  
  151. }

SnakeHead.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class FoodMaker : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static FoodMaker _instance;
  10. public static FoodMaker Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17. public int xlimit = ;
  18. public int ylimit = ;
  19. //x轴活动空间不对称问题,对x轴的偏移值
  20. public int xoffset = ;
  21. public GameObject foodPrefab;
  22. public GameObject rewardPrefab;
  23. public Sprite[] foodSprites;
  24. private Transform foodHolder;
  25.  
  26. private void Awake()
  27. {
  28. _instance = this;
  29. }
  30.  
  31. private void Start()
  32. {
  33. foodHolder = GameObject.Find("FoodHolder").transform;
  34. MakeFood(false);
  35. }
  36.  
  37. public void MakeFood(bool isReward)
  38. {
  39. int index = Random.Range(,foodSprites.Length);
  40. GameObject food = Instantiate(foodPrefab);
  41. food.GetComponent<Image>().sprite = foodSprites[index];
  42. food.transform.SetParent(foodHolder,false);
  43. int x = Random.Range(-xlimit + xoffset,xlimit);
  44. int y = Random.Range(-ylimit,ylimit);
  45. food.transform.localPosition = new Vector3(x * , y * , );
  46. //food.transform.localPosition = new Vector3( x, y, 0);
  47. if(isReward==true)
  48. {
  49. GameObject reward = Instantiate(rewardPrefab);
  50. reward.transform.SetParent(foodHolder, false);
  51. x = Random.Range(-xlimit + xoffset, xlimit);
  52. y = Random.Range(-ylimit, ylimit);
  53. reward.transform.localPosition = new Vector3(x * , y * , );
  54. }
  55. }
  56.  
  57. public void Home()
  58. {
  59. UnityEngine.SceneManagement.SceneManager.LoadScene();
  60. }
  61. }

FoodMaker.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class MainUIController : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static MainUIController _instance;
  10. public static MainUIController Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17.  
  18. public int score = ;
  19. public int length = ;
  20. public Text msgText;
  21. public Text scoreText;
  22. public Text lengthText;
  23. public Image bgImage;
  24. private Color tempColor;
  25.  
  26. public Image pauseImage;
  27. public Sprite[] pauseSprites;
  28. public bool isPause = false ;
  29.  
  30. void Awake()
  31. {
  32. _instance = this;
  33. }
  34.  
  35. private void Update()
  36. {
  37. switch (score / )
  38. {
  39. case :
  40. case :
  41. case :
  42. break;
  43. case :
  44. case :
  45. ColorUtility.TryParseHtmlString("#CCEEFFFF",out tempColor);
  46. bgImage.color=tempColor;
  47. msgText.text = "阶段" + ;
  48. break;
  49. case :
  50. case :
  51. ColorUtility.TryParseHtmlString("#CCEEFFFF", out tempColor);
  52. bgImage.color = tempColor;
  53. msgText.text = "阶段" + ;
  54. break;
  55. case :
  56. case :
  57. ColorUtility.TryParseHtmlString("#CCFFDBFF", out tempColor);
  58. bgImage.color = tempColor;
  59. msgText.text = "阶段" + ;
  60. break;
  61. case :
  62. case :
  63. ColorUtility.TryParseHtmlString("#EBFFCCFF", out tempColor);
  64. bgImage.color = tempColor;
  65. msgText.text = "阶段" + ;
  66. break;
  67. case :
  68. case :
  69. case :
  70. ColorUtility.TryParseHtmlString("#FFDACCFF", out tempColor);
  71. bgImage.color = tempColor;
  72. msgText.text = "阶段 x";
  73. break;
  74. }
  75. }
  76.  
  77. public void UpdateUI(int s = ,int l = )
  78. {
  79. score += s;
  80. length += l;
  81. scoreText.text ="得分:\n"+score;
  82. lengthText.text = "长度\n" + length;
  83. }
  84.  
  85. public void Pause()
  86. {
  87. isPause = !isPause;
  88. if(isPause)
  89. {
  90. Time.timeScale = ;
  91. pauseImage.sprite = pauseSprites[];
  92. }
  93. else
  94. {
  95. Time.timeScale = ;
  96. pauseImage.sprite = pauseSprites[];
  97. }
  98. }
  99. }

MainUIController.cs

游戏贪吃蛇死亡处理

  添加游戏死亡标记

  1. private bool isDie = false;

  判断游戏死亡时触发的粒子特效

  1. void Die()
  2. {
  3. CancelInvoke();
  4. isDie = true;
  5. Instantiate(dieEffect);
  6. StartCoroutine(GameOver(1.0f));
  7. }

  通过Unity协成进行游戏的重新开始

  1. IEnumerator GameOver(float t)
  2. {
  3. yield return new WaitForSeconds(t);
  4. UnityEngine.SceneManagement.SceneManager.LoadScene();
  5. }

  

  游戏结束时候记录最高得分

  1. void Die()
  2. {
  3. CancelInvoke();
  4. isDie = true;
  5. Instantiate(dieEffect);
  6. //记录游戏的最后长度
  7. PlayerPrefs.SetInt("last1",MainUIController.Instance.length);
  8. PlayerPrefs.SetInt("lasts", MainUIController.Instance.score);
  9. //当游戏长度大于最高得分时
  10. if (PlayerPrefs.GetInt("bests", )<MainUIController.Instance.score)
  11. {
  12. //将当前游戏长度和分数记录到best1和bests当中
  13. PlayerPrefs.SetInt("best1", MainUIController.Instance.length);
  14. PlayerPrefs.SetInt("bests", MainUIController.Instance.score);
  15. }
  16. StartCoroutine(GameOver(1.0f));
  17. }
  1. 1、存储值://本地化存储方式,一般用在保存玩家的偏好设置中,常见于玩家设置,游戏分数存取…………
  2.  
  3.   PlayerPrefs.SetFloat(string key,float value); //通过key 与value 存储,就像键值对一样。
  4.  
  5.   PlayerPrefs.SetInt(string key,Int value);
  6.  
  7.   PlayerPrefs.SetString(string key,string value);
  8.  
  9. 2、读取值:
  10.  
  11.   PlayerPrefs.GetFloat(string key); //通过key得到存储的value值
  12.  
  13.   PlayerPrefs.GetInt(string key);
  14.  
  15.   PlayerPrefs.GetString(string key);

Unity 中PlayerPrefs类实现数据本地化存储

用户设置的存储

  添加StartUIController.cs脚本控制Gary开始场景界面

  获得Gary开始场景界面Text文本控件

  1. public Text lastText;
  2. public Text bestText;

  对文本控件的值进行读取刷新

  1. private void Awake()
  2. {
  3. lastText.text = "上次:长度" + PlayerPrefs.GetInt("last1",0) + ",分数" + PlayerPrefs.GetInt("lasts",0);
  4. lastText.text = "最好:长度" + PlayerPrefs.GetInt("best1", 0) + ",分数" + PlayerPrefs.GetInt("bests", 0);
  5. }

  Gary场景中创建一个空物体游戏对象ScriptHolder挂在游戏脚本

  

  实现点击开始进入场景功能

  切换场景方法

  1. public void StartGame()
  2. {
  3. UnityEngine.SceneManagement.SceneManager.LoadScene(1);
  4. }

  Gary场景中Start添加onClick()点击事件

(可以看到此时已经实现上次分数以及最高分数的存储)

  动态绑定选择游戏皮肤、模式

  存储玩家的选择

  1. private void Start()
  2. {
  3. if (PlayerPrefs.GetString("sh", "sh01") == "sh01")
  4. {
  5. blue.isOn = true;
  6. PlayerPrefs.SetString("sh", "sh01");
  7. PlayerPrefs.SetString("sb01", "sb0101");
  8. PlayerPrefs.SetString("sb02", "sb0102");
  9. }
  10. else
  11. {
  12. yellow.isOn = true;
  13. PlayerPrefs.SetString("sh", "sh02");
  14. PlayerPrefs.SetString("sb01", "sb0201");
  15. PlayerPrefs.SetString("sb02", "sb0202");
  16. }
  17. if (PlayerPrefs.GetInt("border", 1) == 1)
  18. {
  19. border.isOn = true;
  20. PlayerPrefs.SetInt("border",1);
  21. }
  22. else
  23. {
  24. noborder.isOn = true;
  25. PlayerPrefs.SetInt("border", 0);
  26. }
  27. }
  28.  
  29. public void BlueSelected(bool isOn)
  30. {
  31. if (isOn)
  32. {
  33. PlayerPrefs.SetString("sh", "sh01");
  34. PlayerPrefs.SetString("sb01", "sb0101");
  35. PlayerPrefs.SetString("sb02", "sb0102");
  36. }
  37. }
  38.  
  39. public void YellowSelected(bool isOn)
  40. {
  41. if (isOn)
  42. {
  43. PlayerPrefs.SetString("sh", "sh02");
  44. PlayerPrefs.SetString("sb01", "sb0201");
  45. PlayerPrefs.SetString("sb02", "sb0202");
  46. }
  47. }
  48.  
  49. public void BorderSelected(bool isOn)
  50. {
  51. if (isOn)
  52. {
  53. PlayerPrefs.SetInt("border",1);
  54. }
  55. }
  56.  
  57. public void NoBorderSelected(bool isOn)
  58. {
  59. if (isOn)
  60. {
  61. //自由模式
  62. PlayerPrefs.SetInt("border", 0);
  63. }
  64. }

完成换肤与数据读取

  使用泛型加载游戏换肤方法

  1. private void Awake()
  2. {
  3. canvas = GameObject.Find("Canvas").transform;
  4. //通过Resources.Load(string path)方法加载资源;
  5. gameObject.GetComponent<Image>().sprite = Resources.Load<Sprite>(PlayerPrefs.GetString("sh", "sh02"));
  6. bodySprites[] = Resources.Load<Sprite>(PlayerPrefs.GetString("sh01", "sh0201"));
  7. bodySprites[] = Resources.Load<Sprite>(PlayerPrefs.GetString("sh02", "sh0202"));
  8. }

  判断游戏模式

  添加一个模式表示位

  1. public bool hasBorder = true;

  游戏初始时默认无边界

  1. void Start()
  2. {
  3. if (PlayerPrefs.GetInt("border", )==)
  4. {
  5. hasBorder = false;
  6. //取消边界上的颜色
  7. foreach(Transform t in bgImage.gameObject.transform)
  8. {
  9. t.gameObject.GetComponent<Image>().enabled = false;
  10. }
  11. }
  12. }

  SnakeHead.cs脚本中对游戏碰到边界死亡进行判定

  1. if (MainUIController.Instance.hasBorder)
  2. {
  3. Die();
  4. }
  5. else
  6. {
  7. switch (collision.gameObject.name)
  8. {
  9. case "Up":
  10. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y + , transform.localPosition.z);
  11. break;
  12. case "Down":
  13. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y - , transform.localPosition.z);
  14. break;
  15. case "Left":
  16. transform.localPosition = new Vector3(-transform.localPosition.x + , transform.localPosition.y, transform.localPosition.z);
  17. break;
  18. case "Right":
  19. transform.localPosition = new Vector3(-transform.localPosition.x + , transform.localPosition.y, transform.localPosition.z);
  20. break;
  21. }
  22. }

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class StartUIController : MonoBehaviour {
  7.  
  8. public Text lastText;
  9. public Text bestText;
  10. public Toggle blue;
  11. public Toggle yellow;
  12. public Toggle border;
  13. public Toggle noborder;
  14.  
  15. private void Awake()
  16. {
  17. lastText.text = "上次:长度" + PlayerPrefs.GetInt("last1",) + ",分数" + PlayerPrefs.GetInt("lasts",);
  18. bestText.text = "最好:长度" + PlayerPrefs.GetInt("best1", ) + ",分数" + PlayerPrefs.GetInt("bests",);
  19. }
  20.  
  21. private void Start()
  22. {
  23. if (PlayerPrefs.GetString("sh", "sh01") == "sh01")
  24. {
  25. blue.isOn = true;
  26. PlayerPrefs.SetString("sh", "sh01");
  27. PlayerPrefs.SetString("sb01", "sb0101");
  28. PlayerPrefs.SetString("sb02", "sb0102");
  29. }
  30. else
  31. {
  32. yellow.isOn = true;
  33. PlayerPrefs.SetString("sh", "sh02");
  34. PlayerPrefs.SetString("sb01", "sb0201");
  35. PlayerPrefs.SetString("sb02", "sb0202");
  36. }
  37. if (PlayerPrefs.GetInt("border", ) == )
  38. {
  39. border.isOn = true;
  40. PlayerPrefs.SetInt("border",);
  41. }
  42. else
  43. {
  44. noborder.isOn = true;
  45. PlayerPrefs.SetInt("border", );
  46. }
  47. }
  48.  
  49. public void BlueSelected(bool isOn)
  50. {
  51. if (isOn)
  52. {
  53. PlayerPrefs.SetString("sh", "sh01");
  54. PlayerPrefs.SetString("sb01", "sb0101");
  55. PlayerPrefs.SetString("sb02", "sb0102");
  56. }
  57. }
  58.  
  59. public void YellowSelected(bool isOn)
  60. {
  61. if (isOn)
  62. {
  63. PlayerPrefs.SetString("sh", "sh02");
  64. PlayerPrefs.SetString("sb01", "sb0201");
  65. PlayerPrefs.SetString("sb02", "sb0202");
  66. }
  67. }
  68.  
  69. public void BorderSelected(bool isOn)
  70. {
  71. if (isOn)
  72. {
  73. PlayerPrefs.SetInt("border",);
  74. }
  75. }
  76.  
  77. public void NoBorderSelected(bool isOn)
  78. {
  79. if (isOn)
  80. {
  81. //自由模式
  82. PlayerPrefs.SetInt("border", );
  83. }
  84. }
  85.  
  86. public void StartGame()
  87. {
  88. UnityEngine.SceneManagement.SceneManager.LoadScene();
  89. }
  90. }

StartUIController.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class MainUIController : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static MainUIController _instance;
  10. public static MainUIController Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17.  
  18. public int score = ;
  19. public int length = ;
  20. public Text msgText;
  21. public Text scoreText;
  22. public Text lengthText;
  23. public Image bgImage;
  24. private Color tempColor;
  25.  
  26. public Image pauseImage;
  27. public Sprite[] pauseSprites;
  28. public bool isPause = false ;
  29. public bool hasBorder = true;
  30.  
  31. void Awake()
  32. {
  33. _instance = this;
  34. }
  35.  
  36. void Start()
  37. {
  38. if (PlayerPrefs.GetInt("border", )==)
  39. {
  40. hasBorder = false;
  41. //取消边界上的颜色
  42. foreach(Transform t in bgImage.gameObject.transform)
  43. {
  44. t.gameObject.GetComponent<Image>().enabled = false;
  45. }
  46. }
  47. }
  48.  
  49. private void Update()
  50. {
  51. switch (score / )
  52. {
  53. case :
  54. case :
  55. case :
  56. break;
  57. case :
  58. case :
  59. ColorUtility.TryParseHtmlString("#CCEEFFFF",out tempColor);
  60. bgImage.color=tempColor;
  61. msgText.text = "阶段" + ;
  62. break;
  63. case :
  64. case :
  65. ColorUtility.TryParseHtmlString("#CCEEFFFF", out tempColor);
  66. bgImage.color = tempColor;
  67. msgText.text = "阶段" + ;
  68. break;
  69. case :
  70. case :
  71. ColorUtility.TryParseHtmlString("#CCFFDBFF", out tempColor);
  72. bgImage.color = tempColor;
  73. msgText.text = "阶段" + ;
  74. break;
  75. case :
  76. case :
  77. ColorUtility.TryParseHtmlString("#EBFFCCFF", out tempColor);
  78. bgImage.color = tempColor;
  79. msgText.text = "阶段" + ;
  80. break;
  81. case :
  82. case :
  83. case :
  84. ColorUtility.TryParseHtmlString("#FFDACCFF", out tempColor);
  85. bgImage.color = tempColor;
  86. msgText.text = "阶段 x";
  87. break;
  88. }
  89. }
  90.  
  91. public void UpdateUI(int s = ,int l = )
  92. {
  93. score += s;
  94. length += l;
  95. scoreText.text ="得分:\n"+score;
  96. lengthText.text = "长度\n" + length;
  97. }
  98.  
  99. public void Pause()
  100. {
  101. isPause = !isPause;
  102. if(isPause)
  103. {
  104. Time.timeScale = ;
  105. pauseImage.sprite = pauseSprites[];
  106. }
  107. else
  108. {
  109. Time.timeScale = ;
  110. pauseImage.sprite = pauseSprites[];
  111. }
  112. }
  113. }

MainUIController.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class FoodMaker : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static FoodMaker _instance;
  10. public static FoodMaker Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17. public int xlimit = ;
  18. public int ylimit = ;
  19. //x轴活动空间不对称问题,对x轴的偏移值
  20. public int xoffset = ;
  21. public GameObject foodPrefab;
  22. public GameObject rewardPrefab;
  23. public Sprite[] foodSprites;
  24. private Transform foodHolder;
  25.  
  26. private void Awake()
  27. {
  28. _instance = this;
  29. }
  30.  
  31. private void Start()
  32. {
  33. foodHolder = GameObject.Find("FoodHolder").transform;
  34. MakeFood(false);
  35. }
  36.  
  37. public void MakeFood(bool isReward)
  38. {
  39. int index = Random.Range(,foodSprites.Length);
  40. GameObject food = Instantiate(foodPrefab);
  41. food.GetComponent<Image>().sprite = foodSprites[index];
  42. food.transform.SetParent(foodHolder,false);
  43. int x = Random.Range(-xlimit + xoffset,xlimit);
  44. int y = Random.Range(-ylimit,ylimit);
  45. food.transform.localPosition = new Vector3(x * , y * , );
  46. //food.transform.localPosition = new Vector3( x, y, 0);
  47. if(isReward==true)
  48. {
  49. GameObject reward = Instantiate(rewardPrefab);
  50. reward.transform.SetParent(foodHolder, false);
  51. x = Random.Range(-xlimit + xoffset, xlimit);
  52. y = Random.Range(-ylimit, ylimit);
  53. reward.transform.localPosition = new Vector3(x * , y * , );
  54. }
  55. }
  56.  
  57. public void Home()
  58. {
  59. UnityEngine.SceneManagement.SceneManager.LoadScene();
  60. }
  61. }

FoodMaker.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6.  
  7. public class SnakeHead : MonoBehaviour {
  8.  
  9. public List<Transform> bodyList = new List<Transform>();
  10. public float velocity=0.35f;
  11. public int step;
  12. private int x;
  13. private int y;
  14. private Vector3 headPos;
  15. private Transform canvas;
  16. private bool isDie = false;
  17.  
  18. public GameObject dieEffect;
  19. public GameObject bodyPrefab;
  20. public Sprite[] bodySprites = new Sprite[];
  21.  
  22. private void Awake()
  23. {
  24. canvas = GameObject.Find("Canvas").transform;
  25. //通过Resources.Load(string path)方法加载资源;
  26. gameObject.GetComponent<Image>().sprite = Resources.Load<Sprite>(PlayerPrefs.GetString("sh", "sh02"));
  27. bodySprites[] = Resources.Load<Sprite>(PlayerPrefs.GetString("sb01", "sb0201"));
  28. bodySprites[] = Resources.Load<Sprite>(PlayerPrefs.GetString("sb02", "sb0202"));
  29. }
  30.  
  31. private void Start()
  32. {
  33. //重复调用
  34. InvokeRepeating("Move",,velocity);
  35. x = ;y = step;
  36. }
  37.  
  38. private void Update()
  39. {
  40. if (Input.GetKeyDown(KeyCode.Space)&&MainUIController.Instance.isPause==false&&isDie==false)
  41. {
  42. CancelInvoke();
  43. InvokeRepeating("Move",,velocity - 0.3f);
  44. }
  45.  
  46. if (Input.GetKeyUp(KeyCode.Space) && MainUIController.Instance.isPause == false && isDie == false)
  47. {
  48. CancelInvoke();
  49. InvokeRepeating("Move", , velocity);
  50. }
  51.  
  52. if (Input.GetKey(KeyCode.W) && y!=-step && MainUIController.Instance.isPause == false && isDie == false)
  53. {
  54. gameObject.transform.localRotation = Quaternion.Euler(, , );
  55. x = ;y = step;
  56. }
  57. if (Input.GetKey(KeyCode.S) && y!=step && MainUIController.Instance.isPause == false && isDie == false)
  58. {
  59. gameObject.transform.localRotation = Quaternion.Euler(, , );
  60. x = ;y = -step;
  61. }
  62. if (Input.GetKey(KeyCode.A) && x!=step && MainUIController.Instance.isPause == false && isDie == false)
  63. {
  64. gameObject.transform.localRotation = Quaternion.Euler(, , );
  65. x = -step;y = ;
  66. }
  67. if (Input.GetKey(KeyCode.D) && x!=-step && MainUIController.Instance.isPause == false && isDie == false)
  68. {
  69. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  70. x = step;y = ;
  71. }
  72. }
  73.  
  74. void Move()
  75. {
  76. //保存下来蛇头移动前的位置
  77. headPos = gameObject.transform.localPosition;
  78. //蛇头向期望位置移动
  79. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  80. if (bodyList.Count > )
  81. {
  82. //由于是双色蛇身,此方法弃用
  83. //将蛇尾移动到蛇头移动前的位置
  84. // bodyList.Last().localPosition = headPos;
  85. //将蛇尾在List中的位置跟新到最前
  86. // bodyList.Insert(0, bodyList.Last());
  87. //溢出List最末尾的蛇尾引用
  88. // bodyList.RemoveAt(bodyList.Count - 1);
  89.  
  90. //从后面开始移动蛇身
  91. for(int i =bodyList.Count-;i>= ;i--)
  92. {
  93. //每一个蛇身都移动到它前面一个
  94. bodyList[i + ].localPosition = bodyList[i].localPosition;
  95. }
  96. //第一个蛇身移动到蛇头移动前的位置
  97. bodyList[].localPosition = headPos;
  98.  
  99. }
  100. }
  101.  
  102. void Grow()
  103. {
  104. int index = (bodyList.Count % == ) ? : ;
  105. GameObject body = Instantiate(bodyPrefab,new Vector3(,,),Quaternion.identity);
  106. body.GetComponent<Image>().sprite = bodySprites[index];
  107. body.transform.SetParent(canvas, false);
  108. bodyList.Add(body.transform);
  109. }
  110.  
  111. void Die()
  112. {
  113. CancelInvoke();
  114. isDie = true;
  115. Instantiate(dieEffect);
  116. //记录游戏的最后长度
  117. PlayerPrefs.SetInt("last1",MainUIController.Instance.length);
  118. PlayerPrefs.SetInt("lasts", MainUIController.Instance.score);
  119. //当游戏长度大于最高得分时
  120. if (PlayerPrefs.GetInt("bests", )<MainUIController.Instance.score)
  121. {
  122. //将当前游戏长度和分数记录到best1和bests当中
  123. PlayerPrefs.SetInt("best1", MainUIController.Instance.length);
  124. PlayerPrefs.SetInt("bests", MainUIController.Instance.score);
  125. }
  126. StartCoroutine(GameOver(1.0f));
  127. }
  128.  
  129. IEnumerator GameOver(float t)
  130. {
  131. yield return new WaitForSeconds(t);
  132. UnityEngine.SceneManagement.SceneManager.LoadScene();
  133. }
  134.  
  135. private void OnTriggerEnter2D(Collider2D collision)
  136. {
  137. if (collision.gameObject.CompareTag("Food"))
  138. {
  139. Destroy(collision.gameObject);
  140. MainUIController.Instance.UpdateUI();
  141. Grow();
  142. if (Random.Range(,)<)
  143. {
  144. FoodMaker.Instance.MakeFood(true);
  145. }
  146. else
  147. {
  148. FoodMaker.Instance.MakeFood(false);
  149. }
  150. }
  151. else if(collision.gameObject.CompareTag("Reward"))
  152. {
  153. Destroy(collision.gameObject);
  154. MainUIController.Instance.UpdateUI(Random.Range(,)*);
  155. Grow();
  156. }
  157. else if(collision.gameObject.CompareTag("Body"))
  158. {
  159. Die();
  160. }
  161. else
  162. {
  163. if (MainUIController.Instance.hasBorder)
  164. {
  165. Die();
  166. }
  167. else
  168. {
  169. switch (collision.gameObject.name)
  170. {
  171. case "Up":
  172. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y + , transform.localPosition.z);
  173. break;
  174. case "Down":
  175. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y - , transform.localPosition.z);
  176. break;
  177. case "Left":
  178. transform.localPosition = new Vector3(-transform.localPosition.x + , transform.localPosition.y, transform.localPosition.z);
  179. break;
  180. case "Right":
  181. transform.localPosition = new Vector3(-transform.localPosition.x + , transform.localPosition.y, transform.localPosition.z);
  182. break;
  183. }
  184. }
  185. }
  186. }
  187.  
  188. }

SnakeHead.cs

添加游戏音乐

  Main场景摄像机上绑定一个Audio Source音乐播放器

  吃到东西和游戏结束时分别播放两个不同的音乐

  1. public AudioClip eatClip;
  2. public AudioClip dieClip;

  

  1. void Grow()
  2. {
  3. //播放贪吃蛇变长音乐
  4. AudioSource.PlayClipAtPoint(eatClip,Vector3.zero);
  5. int index = (bodyList.Count % == ) ? : ;
  6. GameObject body = Instantiate(bodyPrefab,new Vector3(,,),Quaternion.identity);
  7. body.GetComponent<Image>().sprite = bodySprites[index];
  8. body.transform.SetParent(canvas, false);
  9. bodyList.Add(body.transform);
  10. }
  11.  
  12. void Die()
  13. {
  14. //播放死亡音乐
  15. AudioSource.PlayClipAtPoint(dieClip, Vector3.zero);
  16. CancelInvoke();
  17. isDie = true;
  18. Instantiate(dieEffect);
  19. //记录游戏的最后长度
  20. PlayerPrefs.SetInt("last1",MainUIController.Instance.length);
  21. PlayerPrefs.SetInt("lasts", MainUIController.Instance.score);
  22. //当游戏长度大于最高得分时
  23. if (PlayerPrefs.GetInt("bests", )<MainUIController.Instance.score)
  24. {
  25. //将当前游戏长度和分数记录到best1和bests当中
  26. PlayerPrefs.SetInt("best1", MainUIController.Instance.length);
  27. PlayerPrefs.SetInt("bests", MainUIController.Instance.score);
  28. }
  29. StartCoroutine(GameOver(1.0f));
  30. }

  

游戏源代码

  控制蛇和食物脚本

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6.  
  7. public class SnakeHead : MonoBehaviour {
  8.  
  9. public List<Transform> bodyList = new List<Transform>();
  10. public float velocity=0.35f;
  11. public int step;
  12. private int x;
  13. private int y;
  14. private Vector3 headPos;
  15. private Transform canvas;
  16. private bool isDie = false;
  17.  
  18. public AudioClip eatClip;
  19. public AudioClip dieClip;
  20. public GameObject dieEffect;
  21. public GameObject bodyPrefab;
  22. public Sprite[] bodySprites = new Sprite[];
  23.  
  24. private void Awake()
  25. {
  26. canvas = GameObject.Find("Canvas").transform;
  27. //通过Resources.Load(string path)方法加载资源;
  28. gameObject.GetComponent<Image>().sprite = Resources.Load<Sprite>(PlayerPrefs.GetString("sh", "sh02"));
  29. bodySprites[] = Resources.Load<Sprite>(PlayerPrefs.GetString("sb01", "sb0201"));
  30. bodySprites[] = Resources.Load<Sprite>(PlayerPrefs.GetString("sb02", "sb0202"));
  31. }
  32.  
  33. private void Start()
  34. {
  35. //重复调用
  36. InvokeRepeating("Move",,velocity);
  37. x = ;y = step;
  38. }
  39.  
  40. private void Update()
  41. {
  42. if (Input.GetKeyDown(KeyCode.Space)&&MainUIController.Instance.isPause==false&&isDie==false)
  43. {
  44. CancelInvoke();
  45. InvokeRepeating("Move",,velocity - 0.3f);
  46. }
  47.  
  48. if (Input.GetKeyUp(KeyCode.Space) && MainUIController.Instance.isPause == false && isDie == false)
  49. {
  50. CancelInvoke();
  51. InvokeRepeating("Move", , velocity);
  52. }
  53.  
  54. if (Input.GetKey(KeyCode.W) && y!=-step && MainUIController.Instance.isPause == false && isDie == false)
  55. {
  56. gameObject.transform.localRotation = Quaternion.Euler(, , );
  57. x = ;y = step;
  58. }
  59. if (Input.GetKey(KeyCode.S) && y!=step && MainUIController.Instance.isPause == false && isDie == false)
  60. {
  61. gameObject.transform.localRotation = Quaternion.Euler(, , );
  62. x = ;y = -step;
  63. }
  64. if (Input.GetKey(KeyCode.A) && x!=step && MainUIController.Instance.isPause == false && isDie == false)
  65. {
  66. gameObject.transform.localRotation = Quaternion.Euler(, , );
  67. x = -step;y = ;
  68. }
  69. if (Input.GetKey(KeyCode.D) && x!=-step && MainUIController.Instance.isPause == false && isDie == false)
  70. {
  71. gameObject.transform.localRotation = Quaternion.Euler(, , -);
  72. x = step;y = ;
  73. }
  74. }
  75.  
  76. void Move()
  77. {
  78. //保存下来蛇头移动前的位置
  79. headPos = gameObject.transform.localPosition;
  80. //蛇头向期望位置移动
  81. gameObject.transform.localPosition = new Vector3(headPos.x+x,headPos.y+y,headPos.z);
  82. if (bodyList.Count > )
  83. {
  84. //由于是双色蛇身,此方法弃用
  85. //将蛇尾移动到蛇头移动前的位置
  86. // bodyList.Last().localPosition = headPos;
  87. //将蛇尾在List中的位置跟新到最前
  88. // bodyList.Insert(0, bodyList.Last());
  89. //溢出List最末尾的蛇尾引用
  90. // bodyList.RemoveAt(bodyList.Count - 1);
  91.  
  92. //从后面开始移动蛇身
  93. for(int i =bodyList.Count-;i>= ;i--)
  94. {
  95. //每一个蛇身都移动到它前面一个
  96. bodyList[i + ].localPosition = bodyList[i].localPosition;
  97. }
  98. //第一个蛇身移动到蛇头移动前的位置
  99. bodyList[].localPosition = headPos;
  100.  
  101. }
  102. }
  103.  
  104. void Grow()
  105. {
  106. //播放贪吃蛇变长音乐
  107. AudioSource.PlayClipAtPoint(eatClip,Vector3.zero);
  108. int index = (bodyList.Count % == ) ? : ;
  109. GameObject body = Instantiate(bodyPrefab,new Vector3(,,),Quaternion.identity);
  110. body.GetComponent<Image>().sprite = bodySprites[index];
  111. body.transform.SetParent(canvas, false);
  112. bodyList.Add(body.transform);
  113. }
  114.  
  115. void Die()
  116. {
  117. //播放死亡音乐
  118. AudioSource.PlayClipAtPoint(dieClip, Vector3.zero);
  119. CancelInvoke();
  120. isDie = true;
  121. Instantiate(dieEffect);
  122. //记录游戏的最后长度
  123. PlayerPrefs.SetInt("last1",MainUIController.Instance.length);
  124. PlayerPrefs.SetInt("lasts", MainUIController.Instance.score);
  125. //当游戏长度大于最高得分时
  126. if (PlayerPrefs.GetInt("bests", )<MainUIController.Instance.score)
  127. {
  128. //将当前游戏长度和分数记录到best1和bests当中
  129. PlayerPrefs.SetInt("best1", MainUIController.Instance.length);
  130. PlayerPrefs.SetInt("bests", MainUIController.Instance.score);
  131. }
  132. StartCoroutine(GameOver(1.0f));
  133. }
  134.  
  135. IEnumerator GameOver(float t)
  136. {
  137. yield return new WaitForSeconds(t);
  138. UnityEngine.SceneManagement.SceneManager.LoadScene();
  139. }
  140.  
  141. private void OnTriggerEnter2D(Collider2D collision)
  142. {
  143. if (collision.gameObject.CompareTag("Food"))
  144. {
  145. Destroy(collision.gameObject);
  146. MainUIController.Instance.UpdateUI();
  147. Grow();
  148. if (Random.Range(,)<)
  149. {
  150. FoodMaker.Instance.MakeFood(true);
  151. }
  152. else
  153. {
  154. FoodMaker.Instance.MakeFood(false);
  155. }
  156. }
  157. else if(collision.gameObject.CompareTag("Reward"))
  158. {
  159. Destroy(collision.gameObject);
  160. MainUIController.Instance.UpdateUI(Random.Range(,)*);
  161. Grow();
  162. }
  163. else if(collision.gameObject.CompareTag("Body"))
  164. {
  165. Die();
  166. }
  167. else
  168. {
  169. if (MainUIController.Instance.hasBorder)
  170. {
  171. Die();
  172. }
  173. else
  174. {
  175. switch (collision.gameObject.name)
  176. {
  177. case "Up":
  178. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y + , transform.localPosition.z);
  179. break;
  180. case "Down":
  181. transform.localPosition = new Vector3(transform.localPosition.x, -transform.localPosition.y - , transform.localPosition.z);
  182. break;
  183. case "Left":
  184. transform.localPosition = new Vector3(-transform.localPosition.x + , transform.localPosition.y, transform.localPosition.z);
  185. break;
  186. case "Right":
  187. transform.localPosition = new Vector3(-transform.localPosition.x + , transform.localPosition.y, transform.localPosition.z);
  188. break;
  189. }
  190. }
  191. }
  192. }
  193.  
  194. }

SnakeHead.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class FoodMaker : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static FoodMaker _instance;
  10. public static FoodMaker Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17. public int xlimit = ;
  18. public int ylimit = ;
  19. //x轴活动空间不对称问题,对x轴的偏移值
  20. public int xoffset = ;
  21. public GameObject foodPrefab;
  22. public GameObject rewardPrefab;
  23. public Sprite[] foodSprites;
  24. private Transform foodHolder;
  25.  
  26. private void Awake()
  27. {
  28. _instance = this;
  29. }
  30.  
  31. private void Start()
  32. {
  33. foodHolder = GameObject.Find("FoodHolder").transform;
  34. MakeFood(false);
  35. }
  36.  
  37. public void MakeFood(bool isReward)
  38. {
  39. int index = Random.Range(,foodSprites.Length);
  40. GameObject food = Instantiate(foodPrefab);
  41. food.GetComponent<Image>().sprite = foodSprites[index];
  42. food.transform.SetParent(foodHolder,false);
  43. int x = Random.Range(-xlimit + xoffset,xlimit);
  44. int y = Random.Range(-ylimit,ylimit);
  45. food.transform.localPosition = new Vector3(x * , y * , );
  46. //food.transform.localPosition = new Vector3( x, y, 0);
  47. if(isReward==true)
  48. {
  49. GameObject reward = Instantiate(rewardPrefab);
  50. reward.transform.SetParent(foodHolder, false);
  51. x = Random.Range(-xlimit + xoffset, xlimit);
  52. y = Random.Range(-ylimit, ylimit);
  53. reward.transform.localPosition = new Vector3(x * , y * , );
  54. }
  55. }
  56.  
  57. public void Home()
  58. {
  59. UnityEngine.SceneManagement.SceneManager.LoadScene();
  60. }
  61. }

FoodMaker.cs

  场景UI控制脚本 

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class MainUIController : MonoBehaviour {
  7.  
  8. //单例模式
  9. private static MainUIController _instance;
  10. public static MainUIController Instance
  11. {
  12. get
  13. {
  14. return _instance;
  15. }
  16. }
  17.  
  18. public int score = ;
  19. public int length = ;
  20. public Text msgText;
  21. public Text scoreText;
  22. public Text lengthText;
  23. public Image bgImage;
  24. private Color tempColor;
  25.  
  26. public Image pauseImage;
  27. public Sprite[] pauseSprites;
  28. public bool isPause = false ;
  29. public bool hasBorder = true;
  30.  
  31. void Awake()
  32. {
  33. _instance = this;
  34. }
  35.  
  36. void Start()
  37. {
  38. if (PlayerPrefs.GetInt("border", )==)
  39. {
  40. hasBorder = false;
  41. //取消边界上的颜色
  42. foreach(Transform t in bgImage.gameObject.transform)
  43. {
  44. t.gameObject.GetComponent<Image>().enabled = false;
  45. }
  46. }
  47. }
  48.  
  49. private void Update()
  50. {
  51. switch (score / )
  52. {
  53. case :
  54. case :
  55. case :
  56. break;
  57. case :
  58. case :
  59. ColorUtility.TryParseHtmlString("#CCEEFFFF",out tempColor);
  60. bgImage.color=tempColor;
  61. msgText.text = "阶段" + ;
  62. break;
  63. case :
  64. case :
  65. ColorUtility.TryParseHtmlString("#CCEEFFFF", out tempColor);
  66. bgImage.color = tempColor;
  67. msgText.text = "阶段" + ;
  68. break;
  69. case :
  70. case :
  71. ColorUtility.TryParseHtmlString("#CCFFDBFF", out tempColor);
  72. bgImage.color = tempColor;
  73. msgText.text = "阶段" + ;
  74. break;
  75. case :
  76. case :
  77. ColorUtility.TryParseHtmlString("#EBFFCCFF", out tempColor);
  78. bgImage.color = tempColor;
  79. msgText.text = "阶段" + ;
  80. break;
  81. case :
  82. case :
  83. case :
  84. ColorUtility.TryParseHtmlString("#FFDACCFF", out tempColor);
  85. bgImage.color = tempColor;
  86. msgText.text = "阶段 x";
  87. break;
  88. }
  89. }
  90.  
  91. public void UpdateUI(int s = ,int l = )
  92. {
  93. score += s;
  94. length += l;
  95. scoreText.text ="得分:\n"+score;
  96. lengthText.text = "长度\n" + length;
  97. }
  98.  
  99. public void Pause()
  100. {
  101. isPause = !isPause;
  102. if(isPause)
  103. {
  104. Time.timeScale = ;
  105. pauseImage.sprite = pauseSprites[];
  106. }
  107. else
  108. {
  109. Time.timeScale = ;
  110. pauseImage.sprite = pauseSprites[];
  111. }
  112. }
  113. }

MainUIController.cs

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5.  
  6. public class StartUIController : MonoBehaviour {
  7.  
  8. public Text lastText;
  9. public Text bestText;
  10. public Toggle blue;
  11. public Toggle yellow;
  12. public Toggle border;
  13. public Toggle noborder;
  14.  
  15. private void Awake()
  16. {
  17. lastText.text = "上次:长度" + PlayerPrefs.GetInt("last1",) + ",分数" + PlayerPrefs.GetInt("lasts",);
  18. bestText.text = "最好:长度" + PlayerPrefs.GetInt("best1", ) + ",分数" + PlayerPrefs.GetInt("bests",);
  19. }
  20.  
  21. private void Start()
  22. {
  23. if (PlayerPrefs.GetString("sh", "sh01") == "sh01")
  24. {
  25. blue.isOn = true;
  26. PlayerPrefs.SetString("sh", "sh01");
  27. PlayerPrefs.SetString("sb01", "sb0101");
  28. PlayerPrefs.SetString("sb02", "sb0102");
  29. }
  30. else
  31. {
  32. yellow.isOn = true;
  33. PlayerPrefs.SetString("sh", "sh02");
  34. PlayerPrefs.SetString("sb01", "sb0201");
  35. PlayerPrefs.SetString("sb02", "sb0202");
  36. }
  37. if (PlayerPrefs.GetInt("border", ) == )
  38. {
  39. border.isOn = true;
  40. PlayerPrefs.SetInt("border",);
  41. }
  42. else
  43. {
  44. noborder.isOn = true;
  45. PlayerPrefs.SetInt("border", );
  46. }
  47. }
  48.  
  49. public void BlueSelected(bool isOn)
  50. {
  51. if (isOn)
  52. {
  53. PlayerPrefs.SetString("sh", "sh01");
  54. PlayerPrefs.SetString("sb01", "sb0101");
  55. PlayerPrefs.SetString("sb02", "sb0102");
  56. }
  57. }
  58.  
  59. public void YellowSelected(bool isOn)
  60. {
  61. if (isOn)
  62. {
  63. PlayerPrefs.SetString("sh", "sh02");
  64. PlayerPrefs.SetString("sb01", "sb0201");
  65. PlayerPrefs.SetString("sb02", "sb0202");
  66. }
  67. }
  68.  
  69. public void BorderSelected(bool isOn)
  70. {
  71. if (isOn)
  72. {
  73. PlayerPrefs.SetInt("border",);
  74. }
  75. }
  76.  
  77. public void NoBorderSelected(bool isOn)
  78. {
  79. if (isOn)
  80. {
  81. //自由模式
  82. PlayerPrefs.SetInt("border", );
  83. }
  84. }
  85.  
  86. public void StartGame()
  87. {
  88. UnityEngine.SceneManagement.SceneManager.LoadScene();
  89. }
  90. }

StartUIController.cs

Unity3D_(游戏)贪吃蛇的更多相关文章

  1. Java小游戏贪吃蛇

    package snake; import java.awt.BorderLayout;import java.awt.Canvas;import java.awt.Color;import java ...

  2. 用Canvas制作小游戏——贪吃蛇

    今天呢,主要和小伙伴们分享一下一个贪吃蛇游戏从构思到实现的过程~因为我不是很喜欢直接PO代码,所以只copy代码的童鞋们请出门左转不谢. 按理说canvas与其应用是老生常谈了,可我在准备阶段却搜索不 ...

  3. 第一个windows 小游戏 贪吃蛇

    最近用dx尝试做了一个小的贪吃蛇游戏,代码放到github上面:https://github.com/nightwolf-chen/MyFreakout 说一下自己实现的过程: 首先,我把蛇这个抽象成 ...

  4. Unity3D游戏贪吃蛇大作战源码休闲益智手机小游戏完整项目

    <贪吃蛇大作战>一款休闲竞技游戏,不仅比拼手速,更考验玩家的策略. 视频演示: http://player.youku.com/player.php/sid/XMzc5ODA2Njg1Ng ...

  5. 使用JavaScript实现简单的小游戏-贪吃蛇

    最近初学JavaScript,在这里分享贪吃蛇小游戏的实现过程, 希望能看到的前辈们能指出这个程序的不足之处. 大致思路 首先要解决的问题 随着蛇头的前进,尾巴也要前进. 用键盘控制蛇的运动方向. 初 ...

  6. Unity 3D游戏-贪吃蛇类游戏源码:重要方法和功能的实现

    贪吃蛇类游戏源码 本文提供全流程,中文翻译.Chinar坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) 1 头部移动方式 2 生成 Shit 道具 ...

  7. JavaScript面向对象编程小游戏---贪吃蛇

    1 面向对象编程思想在程序项目中有着非常明显的优势: 1- 1 代码可读性高.由于继承的存在,即使改变需求,那么维护也只是在局部模块 1- 2 维护非常方便并且成本较低. ​ 2 这个demo是采用了 ...

  8. 最简单的HTML5游戏——贪吃蛇

    <html> <head> <meta charset="UTF-8"/> <title>贪吃蛇</title> < ...

  9. c++小游戏——贪吃蛇

    #include #include #include #include #include <conio.h> #include #include <windows.h> usi ...

随机推荐

  1. 使用Python基于OpenCV和Tesseract的OCR

    OCR OCR(Optical Character Recognition,光学字符识别)是指电子设备(例如扫描仪或数码相机)检查纸上打印的字符,通过检测暗.亮的模式确定其形状,然后用字符识别方法将形 ...

  2. Springboot实现上传文件接口,使用python的requests进行组装报文上传文件的方法

    记录瞬间 近段时间使用Springboot实现了文件的上传服务,但是在使用python的requests进行post上传时,总是报错. 比如: 1.Current request is not a m ...

  3. Redis5版本集群搭建

    一.简介 1.1 Redis是什么 Redis是一个开源的,使用ANSI C 编写,高性能的Key-Value的NoSQL数据库. 1.2 Redis特点 (1)基于内存 (2)可持久化数据 (3)具 ...

  4. redis 学习(13)-- BitMap

    BitMap 什么是 BitMap BitMap,即位图,其实也就是 byte 数组,用二进制表示,只有 0 和 1 两个数字. 如图所示: 重要 API 命令 含义 getbit key offse ...

  5. jsp页面中使用 splitfn:split注意事项

    我们有一个 字段存储内容是  xxxx意见~~@~~是 在页面上需要分开显示,格式为 xxx意见 是 使用 ${fn:split(comments, '~~@~~')[1]} 来分割是发现出现@符文字 ...

  6. luogu P3620 [APIO/CTSC 2007]数据备份

    luogu 首先如果一条线不是了连接的相邻两个位置一定不优,把它拆成若干连接相邻位置的线.所以现在问题是有\(n\)个物品,选\(k\)个,要求选的位置不能相邻,求最小总和 如果没有选的位置不能相邻这 ...

  7. nginx(五)- linux下安装nginx与配置

    linux系统为Centos 64位 准备目录 [root@instance-3lm099to ~]# mkdir /usr/local/nginx [root@instance-3lm099to ~ ...

  8. Linux下nouveau操作和GPU的操作,nouveau拯救

    之前也提到了,旧机器上有一块NVIDIA的显卡,装了ubuntu16.04后一直没有安装驱动.这周算是有点时间,就差点作了死. 首先必须澄清,这个不是正确的安装过程,起码我就报了memory erro ...

  9. scala下划线的作用

    https://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala Existent ...

  10. php 多肽实例

    多态定义:只关心一个接口或者基类,而不关心一个对象的具体类.(同一类型,不同结果) 这里两个例子: 第一个,我们发现,基类定义了标准,子类进行了自我规则的实现.这是多态的一个要求.同时,这是满足重写: ...