服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - unity实现简单的贪吃蛇游戏

unity实现简单的贪吃蛇游戏

2022-11-09 14:02肖尘 C#

这篇文章主要为大家详细介绍了unity实现简单的贪吃蛇游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了unity实现简单贪吃蛇游戏的具体代码,供大家参考,具体内容如下

unity实现简单的贪吃蛇游戏

SatUIController代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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实现简单的贪吃蛇游戏

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_50642897/article/details/115310370

延伸 · 阅读

精彩推荐
  • C#C# 中杨辉三角的实现

    C# 中杨辉三角的实现

    这篇文章主要介绍了C# 中杨辉三角的实现的相关资料,希望通过本文大家能掌握这部分内容,需要的朋友可以参考下...

    Maze-Mozo6162022-01-24
  • C#浅析c# 接口

    浅析c# 接口

    这篇文章主要介绍了c# 接口的相关资料,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下。...

    莫得感情的代码机器4732022-09-27
  • C#c# 实现模糊PID控制算法

    c# 实现模糊PID控制算法

    这篇文章主要介绍了c# 实现模糊PID控制算法的示例代码,帮助大家更好的理解和使用c#编程语言,感兴趣的朋友可以了解下...

    eflay10892022-10-24
  • C#实例代码讲解c# 线程(上)

    实例代码讲解c# 线程(上)

    这篇文章主要介绍了讲解c# 线程的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...

    HueiFeng3862022-09-20
  • C#C# 计算标准偏差相当于Excel中的STDEV函数实例

    C# 计算标准偏差相当于Excel中的STDEV函数实例

    下面小编就为大家带来一篇C# 计算标准偏差相当于Excel中的STDEV函数实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看...

    C#教程网8702021-12-22
  • C#C#使用private font改变PDF文件的字体详解

    C#使用private font改变PDF文件的字体详解

    这篇文章主要给大家介绍了关于C#使用private font改变PDF文件的字体的相关资料,文中通过示例代码以及图片介绍的非常详细,对大家的学习或者工作具有一...

    E-iceblue11932022-02-25
  • C#C# 设计模式系列教程-模板方法模式

    C# 设计模式系列教程-模板方法模式

    模板方法模式通过把不变的行为搬移到超类,去除了子类中的重复代码,子类实现算法的某些细节,有助于算法的扩展。...

    Wang Juqiang9072021-11-23
  • C#dotNet中的反射用法入门教程

    dotNet中的反射用法入门教程

    这篇文章主要介绍了dotNet中的反射用法,较为详细的分析了.Net中关于反射的概念,使用方法与相关注意事项,需要的朋友可以参考下...

    礼拜一11832021-11-11