预览
前期准备
- 准备材质,图片
- 建立文件夹包括预置键、场景、脚本、材质以及图片
- 使用软件:VS2017、Unity3D
正式制作
1.创造物体
- 创建Quad对象,作为贪吃蛇游戏的背景,附加材质
- 添加灯光效果(2D的工程没有灯光,需要自己添加)
- 创建Cube物体,需要加上刚体(去除重力(Use Gravity),增加碰撞检测(Is T))
- 创建Cube物体,作为蛇身的预置键(拖入相应的文件夹里),需要加上刚体
- 创建Cube物体,作为食物的预置键(拖入相应的文件夹里),需要加上刚体,添加新标签food,并将其添加给food物体
为以上物体配上相应的素材
2.编写代码
//代码如下:
##该脚本赋于蛇头
##该脚本绑定对象为预置键 蛇身(SnakeBody)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class SnakeMove : MonoBehaviour {
List<Transform> body = new List<Transform>();//定义蛇身队列
Vector2 direction = Vector2.up;
public GameObject snakeBody;//定义对象蛇身
private bool flag;//设置开关
float speed = 0.3f;
void Move(){
Vector2 position = transform.position;
if (flag)//触碰食物(开关)时,先生成身体再移动
{
GameObject bodypfb = (GameObject)Instantiate(snakeBody, position, Quaternion.identity);
body.Insert(0, bodypfb.transform);
flag = false;//增长指令结束后关闭开关
}
else if (body.Count > 0)
{
body.Last().position = position;
body.Insert(0, body.Last().transform);
body.RemoveAt(body.Count - 1);
}
this.transform.Translate(direction);
}
// Use this for initialization
void Start () {
InvokeRepeating("Move", speed, speed);//蛇身移动速度
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.LeftArrow)|| Input.GetKey(KeyCode.A))
{
direction = Vector2.left;
}
else if (Input.GetKey(KeyCode.RightArrow)||Input.GetKey(KeyCode.D))
{
direction = Vector2.right;
}
else if (Input.GetKey(KeyCode.UpArrow)||Input.GetKey(KeyCode.W))
{
direction = Vector2.up;
}
else if (Input.GetKey(KeyCode.DownArrow)||Input.GetKey(KeyCode.S))
{
direction = Vector2.down;
}
}
void OnTriggerEnter(Collider coll)
{
if (coll.gameObject.CompareTag("food"))
{
Destroy(coll.gameObject);//碰到对象就销毁该对象
flag = true;//开关打开
}
}
}
##该脚本赋于摄像机
##该脚本绑定对象为预置键 食物(food)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FoodCrete : MonoBehaviour {
public GameObject s_food;
public int x_limt = 30;
public int y_limt = 16;
void Food()
{
int x = Random.Range(-x_limt, x_limt);//x的确定生成范围
int y = Random.Range(-y_limt, y_limt);//x的确定生成范围
Instantiate(s_food, new Vector2(x, y), Quaternion.identity);//生成(对象,范围,不旋转)
}
// Use this for initialization
void Start () {
InvokeRepeating("Food", 2, 3);//重复生成,从第二秒开始,每三秒生成一个(调用Food)
}
// Update is called once per frame
void Update () {
}
}
来源:oschina
链接:https://my.oschina.net/u/4462178/blog/3212039