版权声明:
- 本文原创发布于博客园"优梦创客"的博客空间(网址:
http://www.cnblogs.com/raymondking123/
)以及微信公众号"优梦创客"(微信号:unitymaker) - 您可以自由转载,但必须加入完整的版权声明!
贪吃蛇与方块
- 主要玩法:贪吃蛇吃食物,吃到食物后根据相应数值增加身体长度,如果贪吃蛇碰到方块后,根据方块的数值逐渐减少贪吃蛇身体长度,如果贪吃蛇长度为0时,游戏结束,场景中会有一下墙壁阻挡贪吃蛇的左右移动。
- 角色操作:点击鼠标左键,并在屏幕上左右移动,可以控制贪吃蛇在场景中左右移动,贪吃蛇要吃食物,并且要躲避方块,或者消除方块。
- 游戏计分规则:贪吃蛇要撞击方块(消除方块),方块上都有对应数值,贪吃蛇消除一个方块,根据方块上的数值增加分数。
- 原版游戏画面:
实际游戏运行画面:
通过脚本固定窗口大小(此脚本可以挂在到任意的游戏对象上):
void Start ()
{
Screen.SetResolution(768, 1024, false);
}
贪吃蛇生成:
public void SpawnBodyParts()
{
firstPart = true;
//Add the initial BodyParts
for (int i = 0; i < initialAmount; i++)
{
//Use invoke to avoid a weird bug where the snake goes down at the beginning.
Invoke("AddBodyPart", 0.1f);
}
}
贪吃蛇移动:
- 主要就是检测鼠标是否在屏幕上,通过鼠标左键按下并左右移动来控制贪吃蛇的左右移动,并不用定位坐标,仅检测鼠标左右移动来控制贪吃蛇的左右移动。
贪吃蛇可以会自动向前移动,碰到方块会停顿一下,方块消除后并且贪吃蛇不为0,则贪吃蛇继续向前移动,如果贪吃蛇为0时,游戏结束。
float curSpeed = speed; //Always move the body Up if(BodyParts.Count > 0) BodyParts[0].Translate(Vector2.up * curSpeed * Time.smoothDeltaTime); //check if we are still on screen float maxX = Camera.main.orthographicSize * Screen.width / Screen.height; if (BodyParts.Count > 0) { if (BodyParts[0].position.x > maxX) //Right pos { BodyParts[0].position = new Vector3(maxX - 0.01f, BodyParts[0].position.y, BodyParts[0].position.z); } else if (BodyParts[0].position.x < -maxX) //Left pos { BodyParts[0].position = new Vector3(-maxX + 0.01f, BodyParts[0].position.y, BodyParts[0].position.z); } }
贪吃蛇吃食物:
贪吃蛇吃到食物后,根据食物上的数值增加身体。
public class FoodBehavior : MonoBehaviour { [Header("Snake Manager")] SnakeMovement SM; [Header("Food Amount")] public int foodAmount; // Use this for initialization void Start () { SM = GameObject.FindGameObjectWithTag("SnakeManager").GetComponent<SnakeMovement>(); foodAmount = Random.Range(1, 10); transform.GetComponentInChildren<TextMesh>().text = "" + foodAmount; } // Update is called once per frame void Update () { if (SM.transform.childCount > 0 && transform.position.y - SM.transform.GetChild(0).position.y < -10) Destroy(this.gameObject); } private void OnTriggerEnter2D(Collider2D collision) { Destroy(this.gameObject); } }
菜单系统:
计分:
void Start () { //Initially, set the menu and Score is null SetMenu(); SCORE = 0; //Initialize some booleans speedAdded = false; //Load the best score BESTSCORE = PlayerPrefs.GetInt("BESTSCORE"); }
粒子系统:
-贪吃蛇碰撞方块就会触发粒子系统。
摄像机控制:
```
public class CameraMovement : MonoBehaviour
{
[Header("Snake Container")]
public Transform SnakeContainer;
Vector3 initialCameraPos;
// Use this for initialization
void Start ()
{
initialCameraPos = transform.position;
}
// Update is called once per frame
void Update ()
{
if(SnakeContainer.childCount > 0)
transform.position = Vector3.Slerp(transform.position,
(initialCameraPos + new Vector3(0,SnakeContainer.GetChild(0).position.y - Camera.main.orthographicSize/2,0)),
0.1f);
}
}
```