Volearix
Volearix

Reputation: 1593

Unity lerp doesn't lerp, it just moves immediately

I cannot for life of me figure this one out. This exact code works correctly for my Camera.Main object. My door needs to Lerp up when activated by an external switch, but for some reason no matter what value I put in there it immediately jumps up, it doesn't slowly move up like I would prefer. This code is placed in my void Update() block, any ideas? What am I doing wrong, am I misunderstanding the use of Lerp?

private Transform objTransform = null;
public bool isDoorOpen = false;
private Vector3 posDoorStart;
public Vector3 posDoorEnd;
public float DoorSmoothing = 2.0f;

// Use this for initialization
void Start () {
    objTransform = transform;
    posDoorStart = transform.position;
}

void Update() {
    if (isDoorOpen)
    {
        float smoothing = DoorSmoothing;
        // Also tried this...
        // float smoothing = DoorSmoothing * Time.deltaTime;
        transform.position = Vector3.Lerp(posDoorStart, posDoorEnd, smoothing);
    }
}

Transform starting values: enter image description here

Gate script values: enter image description here

Also, on occasion if I set the lerp too low, as in this example, it only partially moves to the location I want. It has to hit around 1.5 before it'll go all the way up, otherwise I get something like this...

enter image description here

Upvotes: 1

Views: 3438

Answers (1)

Volearix
Volearix

Reputation: 1593

Got the door working peeeeeerfectly! Extremely smooth and no the isDoorOpen variable can be private. Just generated a public method to kick off the door opening. Tried to put the Time.time setting in the Start method, figured out that made a silly jump for the first movement, set it at the time of activation and fixed all the issues. Door is fixed.

private Transform objTransform = null;
private float startTime;
private float DistanctToTravel = 0.0f;
private bool isDoorOpen = false;
private Vector3 posDoorStart;

public Vector3 posDoorEnd;
public float DoorSmoothing = 1.0f;

void Start () {
    objTransform = transform;
    posDoorStart = transform.position;
}

void Update() {
    if (objTransform != null)
    {
        if (isDoorOpen)
        {
            float distCovered = (Time.time - startTime) * DoorSmoothing;
            float smoothing = distCovered / DistanctToTravel;
            transform.position = Vector3.Lerp(posDoorStart, posDoorEnd, smoothing);
        }
    }
}

public void OpenDoor(){
    startTime = Time.time;
    isDoorOpen = true;
    DistanctToTravel = Vector3.Distance (posDoorEnd, posDoorStart);
}

Upvotes: 2

Related Questions