Search code examples
c#unity-game-enginetouch

How to make the character move along the axis using touch?


I have the following code it works, but I don't know how it works.

void Update()
{
#if UNITY_ANDROID

    if(Input.touchCount>0 && Input.GetTouch(0).phase == TouchPhase.Moved )
    {
        Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
        float offset = touchDeltaPosition.x * 40f / 18 * Mathf.Deg2Rad;
        transform.position += new Vector3(0f, 0f, offset);
        transform.position = new Vector3(0f, 0f, Mathf.Clamp(transform.position.z, -7.1f, 7.1f));
    }     
#endif   
}

I need to move the player along the axis by touch, for example, like in the game Cube Surfer!

What I want to get (I used android emulator):

enter image description here

The code I wrote based on the answers below works well at 720x1280, but if you set the resolution to 1440x2960, the controls become too sharp. I know why this is happening because touch.delta is getting too big.

My code:

if (Input.touchCount > 0)
{
    var t = Input.GetTouch(0);

    var delta = t.deltaPosition;

    if (delta != Vector2.zero)
    {
        var offset = transform.position;

        offset.x += delta.x * Sensitivity * Time.deltaTime;

        offset.x = Mathf.Clamp(offset.x, -4f, 4f);

        transform.position = offset;
    }
}

How to fix it?

ScreenToWorldPoint this does not fit because the player moves along a spline.

Thank for help


Solution

  • float worldWidth         = 14f;  //serialized, example value
    float ratioScreenToWorld = 2.0f; //serialized, example value
    
    float screenWidth        = (float) Screen.width;
    
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Moved)
        {
            float horizontal = touch.deltaPosition.x;
            transform.position +=
                new Vector3(0f, 0f, horizontal * (worldWidth / screenWidth) * ratioScreenToWorld);
            //clamp, or whatever
        }
    }
    

    The root of your woes is that you're not normalizing the movement of the finger to some standard.

    With ratioScreenToWorld = 1f, this code maps an offset of the finger on the screen to an offset of the object on the path. The width of the path is specified by worldWidth. Upon changing ratioScreenToWorld it re-proportionates that mapping, e.g. with ratioScreenToWorld = 0.5f in layman terms, "moving your finger across the full screen moves the object on the road/path by half the width of the path".