0

我必须将对象从 -10 移动到 +10 x 位置。但是我想从零 x.point 开始我的对象移动,我怎样才能在中间位置开始我的 lerp?

Edit2:对象应该从 x = 0 位置开始并移动到 +10 x 位置并转到 -10 x 位置,然后再次 +10 x、-10 x 像一个循环。

Vector3 pos1, pos2, pos0, pos3;
void Start()
{
    pos0 = transform.position;

    pos1 = pos0 + new Vector3(10, 0, 0);

    pos2 = pos0 - new Vector3(10, 0, 0);

    pos3 = pos1;
}
float time = 0.5f;
void FixedUpdate()
{ 
    time += Mathf.PingPong(Time.time * 0.5f, 1.0f);
    transform.position = Vector3.Lerp(pos2, pos1, time);
}
4

2 回答 2

3

来自https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html的 Unity API 文档

public static Vector3 Lerp(Vector3 a, Vector3 b, float t);

当 t = 0 时返回 a。当 t = 1 时返回 b。当 t = 0.5 时,返回 a 和 b 之间的中间点。

在 x = 0 正好在起点和终点之间的这种对称情况下,您可以使用 lerp 和 t 从 t = 0.5 开始。也许是这样的:

Vector3 pos1, pos2, pos0, pos3;

private float t;

void Start()
{
    pos0 = transform.position;
    pos1 = pos0 + new Vector3(10, 0, 0);
    pos2 = pos0 - new Vector3(10, 0, 0);
    pos3 = pos1;

    t = 0.5
}

void FixedUpdate()
{ 
    t += Mathf.PingPong(Time.deltaTime * 0.5f, 1.0f);
    transform.position = Vector3.Lerp(pos2, pos1, t);
}

正如@BugFinder 所指出的,您可能应该使用Time.deltaTime而不是Time.time

于 2019-05-01T13:29:59.007 回答
1

这是我将如何处理它:

Vector3 ToPos;
Vector3 FromPos;

void Start()
{
    ToPos = transform.position + new Vector3(10, 0, 0);
    FromPos = transform.position - new Vector3(10, 0, 0);
}

// using Update since you are setting the transform.position directly
// Which makes me think you aren't worried about physics to much.
// Also FixedUpdate can run multiple times per frame.
void Update()
{
    // Using distance so it doesnt matter if it's x only, y only z only or a combination
    float range = Vector3.Distance(FromPos, ToPos);
    float distanceTraveled = Vector3.Distance(FromPos, transform.position);
    // Doing it this way so you character can start at anypoint in the transition...
    float currentRatio = Mathf.Clamp01(distanceTraveled / range + Time.deltaTime);

    transform.position = Vector3.Lerp(FromPos, ToPos, currentRatio);
    if (Mathf.Approximately(currentRatio, 1.0f))
    {
        Vector3 tempSwitch = FromPos;
        FromPos = ToPos;
        ToPos = tempSwitch;
    }
}
于 2019-05-01T14:14:55.857 回答