- Home /
How to drag around an object and making it collide with other object 2D
Well i simply wanna make my sprite draggable with mouse/tap and colliding with other object's. So far i found alot of scripts on the internet to move my object around but i cant make it collide with enything and some of the tutorials about this are old.
So if u can send me to a proper tutorial that includes code or write me one i will probobly understand it since i cannot write my own :(
I will be very thankfull !
Answer by Cornelis-de-Jager · Oct 05, 2017 at 11:19 PM
Add the following the gameobject you want to drag. Create a scritp called Drag
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 = Vector3.Lerp (transform.position, curPosition, Time.deltatime);
}
}
Answer by ematsuno · Jan 25, 2019 at 06:54 PM
screenPoint is null on Mousedown, but you're on the right track.
Here's a simple version that does not account for the offset of the mouse-location and the object's offset:
float camDistance;
private void OnMouseDown()
{
camDistance = Vector3.Distance(transform.position, Camera.main.transform.position);
}
private void OnMouseDrag()
{
Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, camDistance);
Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position = Vector3.Lerp(transform.position, objPosition, Time.deltaTime);
}