0
\$\begingroup\$

I got this code that drags a 2d sphere when i touch the screen:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Dragstick : MonoBehaviour {

    private Vector3 offset;

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Vector3 touchPosWorld = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPosWorld2D = new Vector2(touchPosWorld.x, touchPosWorld.y);

            RaycastHit2D hitInformation = Physics2D.Raycast(touchPosWorld2D, Camera.main.transform.forward);
            if (hitInformation.collider != null)
            {
                GameObject touchedObject = hitInformation.transform.gameObject;
                switch (touchedObject.tag)
                {
                    case "Player":
                        Debug.Log("Touched Sphere " + touchedObject.transform.name);
                        touchPosWorld.z = 0f;
                        transform.position = touchPosWorld;
                        break;
                }
            }
        }
    }
}

Thing is, if I move my finger too fast, the drag stops and the sphere drops... also it runs kind of slow when i execute it...

Any help about what am I doing wrong? Maybe I'm making things too complex, drag and drop of a sphere should be really easy but functions in unity have changed a lot.

Thanks in advance!

\$\endgroup\$
  • \$\begingroup\$ Did you try to move this code to FixedUpdate? \$\endgroup\$ – Alexandre Vaillancourt Jan 17 at 23:22
  • \$\begingroup\$ Yup, same result =( \$\endgroup\$ – jsanchezs Jan 17 at 23:44
4
\$\begingroup\$

The only possible problem I see with the code is that you're checking for a raycast hit constantly. Since your finger "moves too fast" it's no longer casting a ray on the object and your collider is now null.

Instead of checking for the object constantly, check for it on your finger down and then move it until the finger is lifted. This is the snippet / pseudo-code I would use for this job:

Touch touch = Input.GetTouch(0);
switch (touch.phase)
{
//When a touch has first been detected, change the message and record the starting position
    case TouchPhase.Began:
        // "Pick up" the ball
        // put the gameobject in some variable global for this script
        message = "Ball picked up ";
        break;

    //Determine if the touch is a moving touch
    case TouchPhase.Moved:
        // Move the ball to current position of your cursor how you want.
        message = "Ball moved ";
        break;

    case TouchPhase.Ended:
        // "Drop" the ball and remove it from the global gameobject you're using
        message = "Dropped ball ";
        break;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.