I have looked for an object dragging script for Unity 2D. I have found a good method on the internet, but it seems it's just working in Unity 3D. It's not good for me as I'm making a 2D game and it's not colliding with the "walls" in that way.
I have tried to rewrite it to 2D, but I have crashed into errors, with Vectors.
I would be very glad if you could help me rewrite it to 2D.
Here's the code what's working in 3D:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(BoxCollider))]
public class Drag : MonoBehaviour {
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown() {
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
The basic method of dragging and dropping an object with the mouse in Unity typically involves adding a Collider component to the object and then using a physics function, such as Overlap Point or Raycast to detect when it's clicked.
How to move an object with the keyboard in Unity. To move an object with the keyboard, or with any other input device, simply multiply the direction of movement you want to apply, such as forward, for example, by the Input Axis you want to use to control it.
For the ones who have problem using this code, I used ScreenPointToRay to use algebraic raycasts (fast) to determine how far the object should be placed from the camera. This works in both orthographic and perspective cameras
Also, the object could use Collider
to able to be dragged around. So there's no point using [RequireComponent(typeof(BoxCollider2D))]
.
The final code which worked fine for me is:
using UnityEngine;
using System.Collections;
public class DragDrop : MonoBehaviour {
// The plane the object is currently being dragged on
private Plane dragPlane;
// The difference between where the mouse is on the drag plane and
// where the origin of the object is on the drag plane
private Vector3 offset;
private Camera myMainCamera;
void Start()
{
myMainCamera = Camera.main; // Camera.main is expensive ; cache it here
}
void OnMouseDown()
{
dragPlane = new Plane(myMainCamera.transform.forward, transform.position);
Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);
float planeDist;
dragPlane.Raycast(camRay, out planeDist);
offset = transform.position - camRay.GetPoint(planeDist);
}
void OnMouseDrag()
{
Ray camRay = myMainCamera.ScreenPointToRay(Input.mousePosition);
float planeDist;
dragPlane.Raycast(camRay, out planeDist);
transform.position = camRay.GetPoint(planeDist) + offset;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With