# Please help me to move my player a fixed distance

player is moving now only when tap on the screen which is what I wanted. but he is not moving in a fixed amount of distance. for example I want him to move 2 units on the X but he move in a different float value each time such as 1.869 units and if i try to move him back to 0 then he always come back to 0 at different values such as 0.126, 0.420 etc

do you have any idea what can I modify in the code to move him the fixed amount of distance?
maybe it’s something to do with the sensitivity of the touch or the velocity?

I did Debuging to check how the player move in real time and to my surprise he is moving the amount needed all the way till the end of the distance but only in CODE. because in the EDITOR in the transform values I can see the X position is a Float…

here is the code as is now:

``````void Update() {

if (Input.touchCount > 0) {

if (Input.GetTouch(0).phase == TouchPhase.Began) {

touchPosition = Input.GetTouch (0).position;

if (touchPosition.x > screenCenter) {
target = 2f;
}
if (touchPosition.x < screenCenter) {
target = -2f;
}
isTap = true;
//moveHorizontal = Mathf.MoveTowards (moveHorizontal, target, sensitivity * Time.deltaTime);
}
}

if (isTap == true) {
moveHorizontal = Mathf.MoveTowards (moveHorizontal, target, sensitivity * Time.deltaTime);
if (moveHorizontal == 2f || moveHorizontal == -2f) {
isTap = false;
}
}

if (isTap == false) {
moveHorizontal = Mathf.MoveTowards (moveHorizontal, 0, sensitivity * Time.deltaTime);
}

movement = new Vector3 (moveHorizontal, 0.0f, 0.0f);
}
``````

second part:

``````    void FixedUpdate () {

rb.velocity = movement * speedHorizontal;

//restrict movement to boundaries
if (transform.position.x <= xMin) {
transform.position = new Vector3 (xMin, transform.position.y, transform.position.z);
}
if (transform.position.x >= xMax) {
transform.position = new Vector3 (xMax, transform.position.y, transform.position.z);
}

//tilt the player when move horizontal
rb.rotation = Quaternion.Euler (0.0f, 0.0f, rb.velocity.x * -tilt);

//keep move forward while playing
rb.velocity += Vector3.forward * speedForward;
}
``````

thank you

This might be too late to answer this question, but i thought it might help others searching for the same thread. The thing is you have to make sure update runs fixed number of times every frame. If you use just “Update” this might not run fixed number of times every frame. So use “Fixed Update” instead. The other way to do this is define your own number, which is the number of times the update should run per frame using the property Time.fixedDeltaTime.