您的位置:首页 > 其它

链表结构(贪吃蛇小游戏)

2015-10-07 15:17 411 查看
实现原理

为蛇的身体每一个节点添加脚本BodyFollow,使其能跟随父节点移动和设置它的子节点

public class BodyFollow : MonoBehaviour {

//下一个节点.
public BodyFollow next;

//本节点当前位置.
Vector3 originalPisition;

//节点移动的方法.
public void Follow(Vector3 gotoPosition)
{
//移动前记录下当前位置.
originalPisition = this.transform.position;

//将节点移动至上一个节点的位置.
this.transform.position = gotoPosition;

//如果存在下一个节点,则递归调用其移动方法.
if(next)
{
next.Follow(originalPisition);
}
}

}


游戏实现过程

1、首先添加一个Cube作为小蛇的头部,再添加一个Cube作为小蛇的身体,拖为预设体,改变它的颜色和大小,使其能跟头部区分开来,然后添加一个Sphere并拖为预设体作为食物

2、在小蛇的身体上添加之前写好的BodyFollow脚本

3、给蛇的头部添加SnakeMove脚本

public class SnakeMove1 : MonoBehaviour {

//获取身体的预设体.
public GameObject bodyPrefab;

//小蛇的移动速度.
public float moveSpeed;

//记时器.
private float timer = 0;

//当前位置.
private Vector3 originalPosition;

//下一个节点.
BodyFollow next;

//最后一个节点.
BodyFollow tail;

void Start ()
{
AddBody();
}

void Update () {

MoveController ();
}

void MoveController()
{
//移动方法.
timer += Time.deltaTime;
if(timer > 1 / moveSpeed)
{
originalPosition = transform.position;
this.transform.Translate(Vector3.forward * 0.8f);
if(next)
{
next.Follow(originalPosition);
}
timer -= 1 / moveSpeed;
}

//方向控制.
if(Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow))
{
this.transform.Rotate(Vector3.up * 90);
}
if(Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow))
{
this.transform.Rotate(Vector3.down * 90);
}

}

//添加身体.
public void AddBody()
{
BodyFollow body = ((GameObject)Instantiate(bodyPrefab, Vector3.one * 9999, Quaternion.identity)).GetComponent<BodyFollow>();

//如果不存在下一个节点,下一个节点就是新生成的那个body,尾部也是新生成的body.
if(!next)
{
next = body;
tail = next;
}

//如果存在,把新生成的body设为下一个几点,尾部就是新生成的body.
else
{
tail.next = body;
tail = body;
}
}

}


剩下吃食物增加身体的方法比较简单,这里就不写了, 简单的链表结构,如果有写得不好的地方还望大家多多提意见哈~

下面是比较完善的Demo,按任意键开始游戏,使用A、D或者←、→控制小蛇的转向

网页版预览

PC版下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: