Как запустить Vector3.Lerp из средней точки? - PullRequest
0 голосов
/ 01 мая 2019

Мне нужно переместить объект из положения от -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);
}

Ответы [ 2 ]

2 голосов
/ 01 мая 2019

Из документации Unity API на https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

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

0 голосов
/ 01 мая 2019

Вот как бы я подошел к этому:

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;
    }
}
...