Vector3.Lerp and cube movement

Hello Guys!
So today, I’ve started experimenting with Linear Interpolation. My goal is to move smoothly cube from “current position” to “end position”. Let’s see my code before we speak about my problem:

public var startPos : Vector3;
public var endPos : Vector3;

public var perc : float = 0.25;


function Start () {

}

function Update () {
startPos = gameObject.transform.position;
{
    if(Input.GetKeyDown(KeyCode.UpArrow)) 
        {
            endPos = new Vector3(transform.position.x + 1, transform.position.y, transform.position.z);
        }
    if(Input.GetKeyDown(KeyCode.DownArrow)) 
        {
            endPos = new Vector3(transform.position.x - 1, transform.position.y, transform.position.z);
        }
    if(Input.GetKeyDown(KeyCode.RightArrow)) 
        {
            endPos = new Vector3(transform.position.x, transform.position.y, transform.position.z - 1);
        }
    if(Input.GetKeyDown(KeyCode.LeftArrow)) 
        {
            endPos = new Vector3(transform.position.x, transform.position.y, transform.position.z + 1);
        }

    transform.position = Vector3.Lerp(startPos, endPos, perc);

}
}

The thing is, that I want ideal, perfect movement from, let’s supose: 0.0.0 to 1.0.0, so I can’t allow player to make input until the cube will be in the right place.
How to do it ?

add a boolean, “moving” or some such, add it to your input if clauses

// don't use equals for position, floats can be slightly (0.0000001 etc.) different
if ((transform.position - endPos).magnitude > 0.01)
{
moving = true;
}
else
{
// snap to end to make exact
moving = false;
transform.position = endPos;
}

if(!moving && <.....input check.... >)
{ ... }
1 Like

You can use units Vector3.MoveTowards function. Makes this sort of thing nice and easy.