Draging an object by touch input
Hello community.
I am new to Unity and I have started a simple project for Android. What I want to do is drag this object in x axis by touch input. I have managed to do it by writing this code:
public class ObjectControl : MonoBehaviour { public Camera camera; private Rigidbody2D rb2D; private float maxWidth; private Renderer rend; void Start() { if (camera == null) { camera = Camera.main; } rb2D = GetComponent<Rigidbody2D>(); rend = GetComponent<Renderer>(); Vector3 edge = new Vector3(Screen.width, Screen.height, 0.0f); Vector3 tarWidth = camera.ScreenToWorldPoint(edge); float objWidth = rend.bounds.extents.x; maxWidth = tarWidth.x - hatWidth; } void FixedUpdate() { Vector3 rawPos = camera.ScreenToWorldPoint(Input.mousePosition); Vector3 objPos = new Vector3(rawPos.x, -2.75f, 0.0f); float objWidth = Mathf.Clamp(objPos.x, -maxWidth, maxWidth); objPos = new Vector3(objWidth, objPos.y, objPos.z); rb2D.MovePosition(objPos); } }
This seemed to work fine, however, when I tapped anywhere on the screen, the object would just go jump there (on x axis always). I didn't want this to happen in my game so I added a piece of code that makes the renderer check if the touch was inside the Object's bounds and if yes, then it would allow movement. It solved the problem but if I draged the Object too fast, my finger would get out of it and thus the movement would stop.
My question: Do you know how I would prevent this movement halt from happening while preserving this way to drag the Object only if it is beeing touched? Or can you suggest any other ways to achieve this movement on x axis and only if the user has grabbed the Object? I have been searching for hours but nothing would help me.. Thanks in advance.