学习内容: 搭建游戏环境,刚体和力的添加,控制小球跳跃给调整上下板的移动和相机跟随增加障碍物触发器
1.首先把场景搭建好,我们要一个有上下板子挡住的大致场景,同时将小球的刚体属性添加好,下一步我们给小球挂一个有向右移动的力的代码,然后加一个键盘控制小球跳跃
2.上下板的长度不可能无限长,所以我们让上下板和相机跟随小球用相对运动移动
//相机跟随
void Start () {
offset = gameObject.transform.position.x - player.transform.position.x;
}
// Update is called once per frame
void Update () {
gameObject.transform.position = new Vector3(offset+ player.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z);
}
\n
//上下板跟随
void Start () {
offset = gameObject.transform.position.x - player.transform.position.x;
}
void Update()
{
FollowPlayerMove();
}
// Update is called once per frame
void FollowPlayerMove () {
gameObject.transform.position = new Vector3(player.transform.position.x+offset,0,0);
}
3.添加障碍物,在小球的运行过程中需要有障碍物,使用障碍物管理器,instantiate函数随机生成不同宽高的障碍物
public class BarrierControl : MonoBehaviour {
public GameObject player;
public GameObject BarrierPre;
public GameObject CurrentBarrier;
public int BarrierInterval = 10;
void Start () {}
void Update () {
AutCreatBarrier();
}
public void AutCreatBarrier()
{
if(player.transform.position.x>CurrentBarrier.transform.position.x)
{
//生成新的障碍物
float targetX = CurrentBarrier.transform.position.x+BarrierInterval;
float targetY = RandomBarrierPositionY();
Vector3 targetPos = new Vector3(targetX,targetY,0);
GameObject g = Instantiate(BarrierPre,targetPos,Quaternion.identity);
g.transform.localScale = new Vector3(g.transform.localScale.x, RandomBarrierSizeY((int)g.transform.position.y),g.transform.localScale.z);
CurrentBarrier = g;
}
}
public float RandomBarrierSizeY(int y)
{
int yAbs = Mathf.Abs(y);
if(yAbs==0)
{
return 6;
}
else
{
return (3 - yAbs) * 2 - 1;
}
}
public float RandomBarrierPositionY()
{
int r = Random.Range(-3,3);
return r;
}}
4.还需要一个触发器,当第一个障碍物碰到触发器,障碍物开始生成