How do I relate the position of a Gui Rec Transform to a gameobject?

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;

    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?

Alright, I figured out why I was having trouble. There are 2 problems with the current code. The first is that the position of the GUI-object is in screen space. This can be resolved by converting its position to a world point by using:


The 2nd problem is how I was calculating the position of the game-object. If the game-object/GUI object start position contained a zero, it would have lead to ‘NaN’ problems. So instead of relating there position through division, I subtracted the GUI’s current position from it’s start and added that to the game objects start position like so:

/*convertedPosition and ConvertedStartPosition are Vector3
values of the Gui's start and current position 
converted using the technique mentioned above.*/
Vector3 distance = convertedPosition - convertedStartPosition;
gameObjectBeingDragged.transform.position = 
new Vector3(gameObjectStartPosition.x + distance.x, gameObjectStartPosition.y + distance.y);

Now the game-object moves as predicted and the headache this problem caused me is gone. :slight_smile: