平衡球迷宫(二)
上一部分我们场景已经搭建好了,接下来我们开始写脚本来控制小球的移动,相机跟随。
(一)小球的移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player: MonoBehaviour
{
Rigidbody rigid;
public float force = 5;
public float reduce = 0.1f;
void Start()
{
rigid = transform.GetComponent<Rigidbody>();
}
void Update()
{
rigid.AddForce(new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) * force);
if (Input.GetKey(KeyCode.Space))
{
rigid.velocity = new Vector3(Mathf.Lerp(rigid.velocity.x, 0, reduce), rigid.velocity.y, Mathf.Lerp(rigid.velocity.z, 0, reduce));
}
}
}
现在小球可以移动了,空格键可以减速,接下来将代码挂载到小球上,现在我们发现一个问题,小球可以移动了,但是相机却没动,我们还要做一个相机跟随。
(二)相机跟随
相机跟随最简单的方法就是直接将主相机挂载到小球上,但是我们这个比较简单,我们用代码来实现相机的跟随,新建一个脚本,然后写入以下代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Xjgs : MonoBehaviour
{
public Transform target;
private Vector3 offset;
void Start()
{
//设置相对偏移
offset = target.position - this.transform.position;
}
void Update()
{
//更新位置
this.transform.position = target.position - offset;
}
}
接下来将代码挂载到主相机中,并将小球挂到脚本中
下一讲继续分享障碍物的随机生成,还有道路移动动画。