Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Moving Player along X-axis

Tags:

c#

unity3d

touch

I am trying to create a player movement along the x-axis based on finger position.

What I need to Happen: Not multi-Touch. I want it so a player can put a single finger down and grab that position. Then check to see if the player dragged finger along screen on x-axis and move player left or right based off where they dragged finger from first touch.

So if they touch the screen and if drag left: move left by speed and if it changes to drag right move right by speed.

Any help would be Awesome.

like image 719
shane Avatar asked Jan 02 '23 02:01

shane


1 Answers

The easiest way would be to stored first touch position and then compare the X with that position:

public class PlayerMover : MonoBehaviour
{
    /// Movement speed units per second
    [SerializeField]
    private float speed;

    /// X coordinate of the initial press
    // The '?' makes the float nullable
    private float? pressX;



    /// Called once every frame
    private void Update()
    {
        // If pressed with one finger
        if(Input.GetMouseButtonDown(0))
            pressX = Input.touches[0].position.x;
        else if (Input.GetMouseButtonUp(0))
            pressX = null;


        if(pressX != null)
        {
            float currentX = Input.touches[0].position.x;

            // The finger of initial press is now left of the press position
            if(currentX < pressX)
                Move(-speed);

            // The finger of initial press is now right of the press position
            else if(currentX > pressX)
                Move(speed);

            // else is not required as if you manage (somehow)
            // move you finger back to initial X coordinate
            // you should just be staying still
        }
    }


    `
    /// Moves the player
    private void Move(float velocity)
    {
        transform.position += Vector3.right * velocity * Time.deltaTime;
    }

}

WARNING: this solution will only work for devices with touch input available (because of Input.touches use).

like image 178
tsvedas Avatar answered Jan 12 '23 08:01

tsvedas