- Home /
How to use gameObject as a drag-able object.
I have a canvas with panels and slots. Right now, the drag only works with images and other UI elements. How can I use the same drag with 2d game objects with scripts and hitboxes attached? I know this is very general, but here is my drag script that is attached to the image or game object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragHandeler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
public static GameObject itemBeingDragged;
Vector3 startPosition;
public void OnBeginDrag (PointerEventData eventData)
{
itemBeingDragged=gameObject;
}
public void OnDrag (PointerEventData eventData)
{
transform.position=Input.mousePosition;
}
public void OnEndDrag (PointerEventData eventData)
{
itemBeingDragged=null;
}
}
Basically, I need to be able to drag the game object while it has various springs and other things attached. Keep in mind that the game object is a child of the slot, which is a child of the panel, which is a child of the canvas. Sorry for the general question, and thanks for any help.
Answer by mcbauer · Jul 09, 2020 at 07:52 PM
@Zanolon It's a bit of a work around, but this is how I was able to do it. I had the same issue you did.
Implement this into a script attached to the object you want to drag around.
It's a bit of a hack because you need to have colliders turned on in order for "OnMouse" events to fire, but the code that moves the object to the mouse can't have colliders on the object or the selected object will fly at the camera. In order to get around this, there is a final step which basically resets everything by clicking the right mouse button.
private KeyCode disableDragKey = KeyCode.A; // used to turn off dragging
private bool isSelected = false; //setup a bool to monitor when you want to drag
// whenever you click on the object, activate dragging and disabled the collision
private void OnMouseDown()
{
isSelected = true;
GetComponent<BoxCollider>().enabled = false; // disable the collider
}
//handle the constant position update to move the object to wherever the mouse is
private void MoveToMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
transform.position = hitInfo.point;
transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
}
}
private void Update()
{
// if the object has been selected, and it collider has been turned off
if (isSelected)
{
MoveToMouse();
}
if (Input.GetMouseButtonDown(1)) // right mouse button to disable dragging
{
isSelected = false; // we no longer want to select the object
GetComponent<BoxCollider>().enabled = true; // re-enable the collider
}
}