Move player horizontal with Touch instead Input.GetAxis (672540)

im trying to replace my keyboard code with a touch system and the result is different. i want my player move right or left only when touching the screen and tilt on that direction and tilt back

this is how my code work for pc keyboard:

 moveHorizontal = Input.GetAxis ("Horizontal");
movement = new Vector3 (moveHorizontal, 0.0f, 0.0f);

in FixedUpdate:

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

-thats above work like a charm! but when i try to set it in touch i dont get the nice smooth movements, because the Update effect the result.. here is how i try it in touch:

in Update:

         if (Input.touchCount > 0) {
                 touchPosition = Input.GetTouch (0).position;
                 if (touchPosition.x > Screen.width / 2) {
                     moveHorizontal = 1;
                 if (Input.GetTouch (0).phase == TouchPhase.Ended) {
                     moveHorizontal = 0f;
                 }
                 } else {
                    moveHorizontal = -1;
                 if (Input.GetTouch (0).phase == TouchPhase.Ended) {
                     moveHorizontal = 0f;
                 }
             }
         }
movement = new Vector3 (moveHorizontal, 0.0f, 0.0f);

in FixedUpdate:

 player.velocity = movement * speedHorizontal;

problem is that everything is going fast and not nice and smooth as in Input.GetAxis. how i can to simulate Input.GetAxis?

thanks for help

found this code but dont get it how to implement it in my case?

Maybe something like this (untested, and not optimised. You’ll need to add the fields for “sensitivity” and “dead” to your script)

if (Input.touchCount > 0) {
   
    float target;
    touchPosition = Input.GetTouch (0).position;
    if (touchPosition.x > Screen.width / 2) {
        target = 1;
    } else {
        target = -1;
    }

    moveHorizontal = Mathf.MoveTowards(moveHorizontal, target, sensitivity * Time.deltaTime);

} else {
    moveHorizontal = (moveHorizontal < dead) ? 0 : Mathf.MoveTowards(moveHorizontal, 0, sensitivity * Time.deltaTime);
}
2 Likes

work like a charm! thank you so much!!!

1 Like