# Question Problem with physics movement using touch controls

Discussion in 'Physics' started by mathiasbc04, Nov 3, 2023.

1. ### mathiasbc04

Joined:
Dec 21, 2020
Posts:
33

Hi, the video demonstrates my problem. I want a character to go from left to right, following my finger's touch position on the x axis. My current script works fine - unless you lift your finger and place it again. If you do that the character will rush to the middle of the screen. I want the player to stay where it is even if the "startPosition" is changed. Here's the script I use for movement:

Code (CSharp):
1. private void Update()
2.     {
3.         if (Input.touchCount > 0)
4.         {
5.             Touch touch = Input.GetTouch(0);
6.
7.             switch (touch.phase)
8.             {
9.                 case TouchPhase.Began:
10.                     startPosition = touch.position;
11.                     break;
12.                 case TouchPhase.Moved:
13.                     // The force on the x axis is calculated...
14.                     // by how far away the finger is from the starting point
15.                     xForce = touch.position.x - startPosition.x;
16.
17.                     // Limit x-axis force to prevent advantages from longer screens
18.                     xForce = Mathf.Clamp(xForce, -maxXForce, maxXForce);
19.                     break;
20.             }
21.
22.             fingerDown = true;
23.         }
24.         else if (playing)
25.         {
26.             fingerDown = false;
27.         }
Code (CSharp):
1.     private void FixedUpdate()
2.     {
3.         if (fingerDown && playing)
4.         {
5.             // Calculations to make it more responsive
6.
7.             // calculate the direction we want to move in and our desired velocity
8.             float targetSpeed = (xForce * sideSpeed);
9.             // calculate the difference between current velocity and desired velocity
10.             float speedDif = targetSpeed - rb.velocity.x;
11.             // Change acceleration rate depending on situation
12.             float accelRate = (Mathf.Abs(targetSpeed) > 0.01f) ? acceleration : decceleration;
13.             // Applies acceleration to speed difference, then raises to a set power so acceleration increases with higher speeds
14.             // finally multiplies by sign to reapply direction
15.             float movement = Mathf.Pow(Mathf.Abs(speedDif) * accelRate, velPower) * Mathf.Sign(speedDif);
16.
17.
18.             // Making the ball move along a slope
19.
20.             if(OnGround())
21.             {
22.                 forceDirection = Vector3.ProjectOnPlane(new Vector3(movement, 0, 0), slopeNormal);
23.             }
24.             else
25.             {
26.                 forceDirection = new Vector3(movement, 0, 0);
27.             }
28.
29.             // Makes the ball move from left ot right
30.             rb.AddForce(new Vector3(forceDirection.x, forceDirection.y, 0));
31.
32.         }