Can not get precise positioning of Rigidbody in Unity3D

If I am understanding this correct, instead of changing the velocity, because to get it to move 1 unit exactly would be near impossible. Instead, why not move the player one unit exactly? Using a Coroutine you can use the Vector3.Lerp method to move from your current position to your desired position over time. Your desired position is 1 unit, or, the distance between each of your lanes from your current position.

void Update(){

    //For Moving Left
    if (Input.GetKeyDown(KeyCode.A))
            StartCoroutine(MoveToPosition(transform, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), 0.5f));
    
    //For Moving Right
    if (Input.GetKeyDown(KeyCode.D))
            StartCoroutine(MoveToPosition(transform, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), 0.5f));
}

public IEnumerator MoveToPosition(Transform transform, Vector3 position, float timeToMove)
    {
        var currentPos = transform.position;
        var t = 0f;
        while (t < 1)
        {
            t += Time.deltaTime / timeToMove;
            transform.position = Vector3.Lerp(currentPos, position, t);
            yield return null;
        }
    }

I presume you are moving left/right on the X axis, if not, simply change the – 1 to the axis that you are moving on. You can change the TimeToMove float to your liking as well.

Hope this helps. If you have any questions feel free to ask!

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top