Object dragging on mobile slow and doesn't follow finger properly
I wrote a script for dragging and dropping an object in my 2D game. It works good if I drag the object slowly with my finger, but if I do that fast, the object looses the connection to the finger and snaps back into the starting position or it just won't move.. Also when I drag the object above another object which is also draggable, sometimes it switches from the object I was already dragging to the object that was on the way of the drag. Does that second issue has anything to do with the order in layer? I have no idea what can I do about the first problem with the speed.. Here's the code: public class Number3Script : MonoBehaviour { [SerializeField] private Transform number3Place; private Vector2 initialPosition; private float deltaX, deltaY; public static bool locked = false; public AudioSource sound; public GameObject glowing;
private void Start()
{
initialPosition = transform.position;
}
private void Update()
{
if (Input.touchCount > 0 && !locked)
{
Touch touch = Input.GetTouch(0);
Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
switch (touch.phase)
{
case TouchPhase.Began:
if (GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos))
{
deltaX = touchPos.x - transform.position.x;
deltaY = touchPos.y - transform.position.y;
glowing.SetActive(true);
}
break;
case TouchPhase.Moved:
if (GetComponent<Collider2D>() == Physics2D.OverlapPoint(touchPos))
{
transform.position = new Vector2(touchPos.x - deltaX, touchPos.y - deltaY);
}
break;
case TouchPhase.Ended:
if (Mathf.Abs(transform.position.x - number3Place.position.x) <= 0.5f &&
Mathf.Abs(transform.position.y - number3Place.position.y) <= 0.5f)
{
transform.position = new Vector2(number3Place.position.x, number3Place.position.y);
sound.Play();
locked = true;
glowing.SetActive(false);
}
else
{
transform.position = new Vector2(initialPosition.x, initialPosition.y);
locked = false;
glowing.SetActive(false);
}
break;
}
}
}
}
Your answer
Follow this Question
Related Questions
Drag and drop Dress up 1 Answer
2D Character movement using OnDrag 0 Answers
Problem when build terrain on android device 0 Answers
Unity WebGL Disable mobile warning 12 Answers
Black Material when camera rotate 1 Answer