在Vectoer3类中有一个Lerp方法,可以让一个物体从一个点到另外一个点。如果要在
这里点加往返运动我们可以借助Mathf.PingPong()这个方法。这个方法会从0-Lenght持续增加,达到最大值后,持续减小,然后到0,如此反复。每次都会返回一个大于0 的值,我们把该值加在某一个固定值上就可以达到往复变大变小的效果。
方法一
using UnityEngine;
using System.Collections;
public class Vector3Lerp : MonoBehaviour {
//起始坐标
public Transform ori;
//终止坐标
public Transform des;
//记录距离起始点的距离
float z = 0;
void Start () {
//记录最开始的Z方向上的位置
z = transform.position.z;
}
// Update is called once per frame
void Update () {
float distance = Mathf.PingPong(Time.time*0.5f, Vector3.Distance(ori.position, des.position));
//每帧都给游戏物体一个新的坐标
transform.position = new Vector3(transform.position.x,transform.position.y,z+ distance);
}
}
方法二:
通过计时器来改变方向
float num = 0.01f;
bool flag = false;
float timer = 1;
void Task02()
{
if (flag)
{
timer -= Time.deltaTime;
if (timer <= 0)
{
flag = false;
}
}
else
{
timer += Time.deltaTime;
if (timer>=1)
{
flag = true;
}
}
sphere.transform.position = Vector3.Lerp(new Vector3(5,1,-5), new Vector3(5, 1, 5),timer);
}
方法三
void Task03()
{
sphere.transform.position = new Vector3(5,1,5*Mathf.Sin(Time.time*2));
}
可以利用数学中的正弦函数,这样的代码最为简洁