SS::STA Game组福利题

C#基础

众所周知,贪吃蛇是早期最受欢迎的游戏之一。而要是需制作它,其中最重要的步骤就是当蛇吃到食物时,蛇身的伸长以及其随着蛇头的移动,现用两种方式实现上述功能,代码如下:

[C# Script]

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
using System.Collections;

using System.Collections.Generic;

using System.Linq;

using UnityEngine;

pubic class snake : MonoBehaviour

{

public List<Transform> bodylist= new List<Transform> ;

public GameObject snakebody;

public Vector3 headpos;

void Update ()

{

if(foodeating) //foodeating用来判定是否吃到食物,简略不表

grow();

move();

}

void move()

{

headpos = this.transform.position;

this.transform.Translate(new Vector3(x,y,z)); //x,y,z的正负判定简略不表

if (bodylist.Count > 0)

{

//方法1

bodylist.Last().position = headpos;

bodylist.Insert(0, bodylist.Last());

bodylist.RemoveAt(bodylist.Count - 1);

//方法2

for (int i = bodylist.Count - 2; i >= 0; i--)

bodylist[i + 1].position = bodylist[i].position;

bodylist[0].position = headpos;

}

}

void grow()

{

GameObject body = Instantiate(snakebody,new Vector3(2000,2000,0),Quaternion.identity); //新身体生成在屏幕外

bodylist.Add(body.transform);

}

}