简体   繁体   中英

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: 在此处输入图片说明

Gate script values: 在此处输入图片说明

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM