I’m trying to create a GUI button that when dragged causes a game-object in the scene to move relative to the GUI’s movement. Here’s my code:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class DragController: MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public static GameObject guiBeingDragged;
public GameObject gameObjectBeingDragged;
private Vector3 guiStartPosition, gameObjectStartPosition;
private Transform myTransform;
void Start()
{
myTransform = transform;
}
public void OnBeginDrag(PointerEventData eventData)
{
guiBeingDragged = gameObject;
guiStartPosition = myTransform.position;
gameObjectStartPosition = gameObjectBeingDragged.transform.position;
}
public void OnDrag(PointerEventData eventData)
{
myTransform.position = Input.mousePosition;
DefineObjectPosition();
}
public void OnEndDrag(PointerEventData eventData)
{
//## this part resets their position to start
guiBeingDragged = null;
myTransform.position = guiStartPosition;
gameObjectBeingDragged.transform.position = gameObjectStartPosition;
}
void DefineObjectPosition()
{
/* The math behind this part is:
(Gui Current Position)*(GameObject Start Position) / (GUI Start Position) = (GameObject Current Position)*/
gameObjectBeingDragged.transform.position =
new Vector3((myTransform.position.x * gameObjectStartPosition.x) / guiStartPosition.x,
((myTransform.position.y * gameObjectStartPosition.y) / guiStartPosition.y));
}
}
It works on the y axis as expected, but it doesn’t move at all on the x. My assumption is that I’m not properly relating their position so I’m not receiving the results I want. So my question is how do I relate the position of a Gui Rec Transform to a game-object?