Unity实现3D贪吃蛇的移动代码
本文实例为大家分享了Unity实现3D贪吃蛇移动的具体代码,供大家参考,具体内容如下
记录一下前段时间写到的一个3D贪吃蛇的移动代码。
链接:Unity实现3D贪吃蛇
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
usingUnityEngine.UI;
publicclassGameManager:MonoBehaviour
{
ListbodyList=newList();//身体位置的列表
privatefloatspeed=2f;//移动速度
publicGameObjectbodyObj;//用来生成的身体对象
ListbodyCreatePostion=newList();//身体部分的transfrom列表
privatefloatTransOffset=1f;//位置间隔
privateListmapAddress=newList();//前进目标在地图上的位置,
publicTransformfirstBody;//第一个身体部件的transfrom
constintrow=100;//地图宽
constintcol=100;//地图高
intstep=1;//步伐
intx=0,z=0;//记录x和z轴的移动量
//Startiscalledbeforethefirstframeupdate
publicVector3[,]map=newVector3[row,col];//地图
//Startiscalledbeforethefirstframeupdate
voidStart()
{
for(inti=0;i0;i--)//刷新后一个的目标为前一个的目标
{
mapAddress[i]=mapAddress[i-1];
}
mapAddress[0]=newVector2(mapAddress[0].x+x,mapAddress[0].y+z);//刷新第一个目标的位置
}
else
{
for(inti=bodyList.Count-1;i>0;i--)//移动
{
bodyList[i].position=Vector3.MoveTowards(bodyList[i].position,
map[(int)mapAddress[i-1].x,(int)mapAddress[i-1].y],Time.deltaTime*speed);
}
bodyList[0].position=Vector3.MoveTowards(transform.position,
map[(int)mapAddress[0].x+x,(int)mapAddress[0].y+z],Time.deltaTime*speed);
}
}
privatevoidOnCollisionEnter(Collisioncollision)//碰撞到了食物就增加身体长度
{
if(collision.collider.tag=="Food")
{
Destroy(collision.collider.gameObject);
GameObjecttmpGameObject=newGameObject();
Vector2tmpVec=newVector2();
tmpGameObject=Instantiate(bodyObj,map[(int)mapAddress[mapAddress.Count-1].x+x,(int)mapAddress[mapAddress.Count-1].y+z],Quaternion.identity);//生成body物体
tmpVec=newVector2(mapAddress[mapAddress.Count-1].x+x,mapAddress[mapAddress.Count-1].y+z);
//增加身体的transform和目标向量
bodyList.Add(tmpGameObject.transform);
mapAddress.Add(tmpVec);
}
}
}
更多有趣的经典小游戏实现专题,分享给大家:
C++经典小游戏汇总
python经典小游戏汇总
python俄罗斯方块游戏集合
JavaScript经典游戏玩不停
java经典小游戏汇总
javascript经典小游戏汇总
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。