在unity3d中经常用线性插值函数Lerp()来在两者之间插值,两者之间可以是两个材质之间、两个向量之间、两个浮点数之间、两个颜色之间,其函数原型如下:
- 例子
- public class Forest : MonoBehaviour
- {
- public GameObject[] obstacles; //路障物体数组
- public float startLength = 50; //路障在道路上出现的开始位置
- public float minLength = 100; //路障距上一个路障的最小距离
- public float maxLength = 200; //路障距上一个路障的最大距离
- private Transform player; //游戏主人公-奔跑者的Transform组件
- private waypoints wayPoints; //与路面相贴合的路线上的脚本组件
- void Awake()
- {
- player = GameObject.FindGameObjectWithTag(Tags.player).transform; //找到游戏主人公-奔跑者并获得它的Transform组件
- wayPoints = transform.Find("waypoints").GetComponent<waypoints>(); //找到与路面相贴合的路线上的脚本组件
- }
- // Use this for initialization
- void Start()
- {
- GenerateObstacle(); //当森林道路被创建出来时,就会自动调用此Start()方法,从而调用此GenerateObstacle()方法
- }
- // 如果主人公跑完了这段道路,则通知GenerateForest类开始运行产生新的道路,并销毁已跑完的这条道路
- void Update ()
- {
- if (player.position.z > transform.position.z+100)
- {
- Camera.main.SendMessage("GenerateForest");
- GameObject.Destroy(this.gameObject);
- }
- }
- void GenerateObstacle()
- {
- float startZ = transform.position.z - 3000; //当前道路在场景中的起始Z坐标
- float endZ = transform.position.z; //当前道路在场景中的结束Z坐标
- float z = startZ + startLength; //将要产生的路障的Z坐标
- while (true)
- {
- z += Random.Range(100, 200); //每隔100多米的距离产生一个路障
- if (z > endZ) //如果将要产生路障的位置超出了这条道路则退出路障产生循环,否则产生路障
- {
- break;
- }
- else
- {
- Vector3 position = GetWayPosByz(z); //调用GetWayPosByz()方法计算路障位置坐标
- int obsIndex = Random.Range(0, obstacles.Length); //产生一个从路障数组里取路障的随机序数
- GameObject.Instantiate(obstacles[obsIndex], position, Quaternion.identity);//实例化路障
- }
- }
- }
- Vector3 GetWayPosByz(float z)
- {
- Transform[] points = wayPoints.points; //在道路上设置的转折点的集合
- int index = 0; //转折点在集合中的序数号
- for (int i = 0; i < points.Length-1; i++)
- { //根据要插入路障的Z值在集合中寻找在哪两个点之间,找到后记下序数号
- if(z<=points[i].position.z && z>=points[i+1].position.z){
- index = i;
- break;
- }
- }
- //使用Lerp函数计算出插入路障处的空间坐标值
- return Vector3.Lerp(points[index + 1].position, points[index].position,(z - points[index + 1].position.z) / (points[index].position.z - points[index +1].position.z));
- }
- }