Mobile drag/release in 3d?

Hi,

I’m new to mobile game development and after following a tutorial on how to make a simple drag/release touch screen script in a 2D project. Basically you drag your finger acroos the phone screen and when you release, force is added to a ball.
I’m wondering what is making this code not work in a 3D project? Here’s the code:

public float power = 10f;
    public float maxDrag = 5f;
    public Rigidbody2D rb;
    public LineRenderer lr;

    Vector3 dragStartPos;
    Touch touch;



    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0)
        {
            touch = Input.GetTouch(0);

            if (touch.phase == TouchPhase.Began)
            {

                DragStart();

            }
            if (touch.phase == TouchPhase.Moved)
            {

                Dragging();

            }
            if (touch.phase == TouchPhase.Ended)
            {

                DragRelease();

            }
        }
    }

    void DragStart()
    {

        dragStartPos = Camera.main.ScreenToWorldPoint(touch.position);
        dragStartPos.z = 0f;
        lr.positionCount = 1;
        lr.SetPosition(0, dragStartPos);

    }

    void Dragging()
    {

        Vector3 draggingPos = Camera.main.ScreenToWorldPoint(touch.position);
        draggingPos.z = 0;
        lr.positionCount = 2;
        lr.SetPosition(1, draggingPos);

    }


    void DragRelease()
    {

        lr.positionCount = 0;
        Vector3 dragReleasePos = Camera.main.ScreenToWorldPoint(touch.position);
        dragReleasePos.z = 0;

        Vector3 force = dragStartPos - dragReleasePos;
        Vector3 clampedForce = Vector3.ClampMagnitude(force, maxDrag) * power;
        rb.AddForce(clampedForce, ForceMode2D.Impulse);

    }

Obviously I’ve changed Rigidbody2D and ForceMode2D to Rigidbody and ForceMode but the line renderer doesn’t start where your finger hits the phone’s screen and there’s no line drag nor force added to the ball. Since it’s Vector3 based, shouldn’t this work in a 3D project?

Since your game is in 3D and works off physics, I have to assume the game’s horizontal plane is XZ, but the screen’s coordinates are in XY. There is a mismatch between the coordinates, preventing you from using the control values directly in the world.

Unless the game is in top-down view, converting your control coordinates from XY to XZ before applying it as a force will probably not be enough. Without knowing the camera relative to the ball, and what you intend to happen specifically on a swipe, it is difficult to give a tailored solution.

1 Like

Ahh of course! Thank you for your fresh set of eyes and help :slight_smile: