Moving an object in 2d using keyboard causes inconsistent behavior

Hello all

I’m trying to move a sprite X pixels in each direction using the keyboard along 0.5 seconds.

my code so far:

using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {

	// Use this for initialization
	void Start () {
	}

    private float speed = 3f;
    private float movementX = 0;
    private float newPosX = 0;

    private bool isMoving = false;

    // Update is called once per frame
	void Update () {
        if (!isMoving)
        {
            movementX = 0;
            newPosX = 0;
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                isMoving = true;
                movementX = -speed * Time.deltaTime;
                newPosX = transform.position.x - renderer.bounds.size.x;
            }
            if (Input.GetKey(KeyCode.RightArrow))
            {
                isMoving = true;
                movementX = speed * Time.deltaTime;
                newPosX = transform.position.x + renderer.bounds.size.x;
            }
        }
        transform.position = new Vector3(transform.position.x + movementX, transform.position.y, transform.position.z);
        if (transform.position.x >= newPosX)
        {
            isMoving = false;
            movementX = 0;
        }
	}
}

Problem is the movement is kind of erratic. sometimes it’s fast, sometimes it’s slow as hell… I’ve tried taking deltaTime into account, but that didn’t seem to help…

Any ideas? Please be easy, I’m a n00b when it comes to Unity :slight_smile:

You’re not taking the DeltaTime into account correctly. As written, you collect the Time.deltaTime once per move, but you need it once per frame. I.e., next time Update is called, there’s a new Time.deltaTime, but your MovementX has already been set and does not change. Try removing both “* Time.deltaTime” from inside the if statement, and instead using it inside the “new Vector3” instead: “transform.position.x + movement * Time.deltaTime”.

Can you substitute what you have on line 35 for this?

 if ( movementX <= 0 ) 
     isMoving = false;
 else 
 {
     transform.position = new Vector3(transform.position.x + movementX * Time.deltaTime, transform.position.y, transform.position.z);
     movementX -= movementX * Time.deltaTime;
}