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;
}
}
You're almost there.
Change the RequireComponent line in your code to:
[RequireComponent(typeof(BoxCollider2D))]
And add a BoxCollider2D component to the object to which you add your script. I just tested it and it works fine.
For the ones who have problem using this code, I removed screenPoint
and replaced it with 10.0f
(which is the distance of the object from the camera). You can use whatever float you need to. Now it works. Also the object need a BoxCollider
or CircleCollider
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 {
private Vector3 offset;
void OnMouseDown()
{
offset = gameObject.transform.position -
Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f));
}
void OnMouseDrag()
{
Vector3 newPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f);
transform.position = Camera.main.ScreenToWorldPoint(newPosition) + offset;
}
}
来源:https://stackoverflow.com/questions/23152525/drag-object-in-unity-2d