It turned out that the reason the dragging did not work is because most of the UI objects were not actual UI elements, but rather sprite renderers. Make sure when you make a canvas that all child objects are UI objects
Drag & drop start position on a perspective camera?
I have a script that allows me to drap and release an image on my canvas. the canvas is using a perspective camera as it's render camera. I have seen multiple tutorials about Drag and drop so this code is made specifically for that. However, those tutorials do not mention how to do this for perspective cameras.
What I want to do is this: when you start dragging the image, it will create a start position of that object. when you top dragging the object, it will use that start position to return the image to it's original position before the dragging started. You can see on the code that I specifically pointed out which code needs to be changed. the code works, but not on perspective cameras, in which, it will cause the image to be moved to a position relevant to the world space, rather than the camera.
What can I change in my code to make this work properly?
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class DragHandler : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
public static GameObject itemBeingDragged;
Ray startPosition;
Vector2 point;
public float distance;
#region IBeginDragHandler implementation
public void OnBeginDrag (PointerEventData eventData)
{
itemBeingDragged = gameObject;
/*-------------------->>>*/ startPosition = transform.position;
distance = Vector2.Distance(transform.position, Camera.main.transform.position);
}
#endregion
#region IDragHandler implementation
public void OnDrag (PointerEventData eventData)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
transform.position = rayPoint;
}
#endregion
#region IEndDragHandler implementation
public void OnEndDrag (PointerEventData eventData)
{
itemBeingDragged = null;
/*-------------------->>>*/ transform.position = startPosition;
}
#endregion
}
If there's something that is unclear, or if you need additional information, please let me know.
Follow this Question
Related Questions
Setting UI element position in physical units during runtime. 0 Answers
Change position of AdMob banner when opening new scene 3 Answers
Respawn Ball to specific spawnpoint after death 1 Answer
OnTriggerEnter and position problem 0 Answers
How to get screen relative position in multi-display environment? 0 Answers