Move a 3d object from world space in the camera UI

I need to move a non-UI object in my scene to a the position of an object on the Canvas. Here is an illustration of what I am trying to do, the worldspace object to move along the red arrow to the UI element:

I have tried lots of things and searched at length, the best I could do was as below (except itdoesn’t quite work):

void FixedUpdate()
{
    Vector2 StartPosition = transform.position;  					
    Vector2 DestinationPosition = Camera.main.ScreenToWorldPoint(canvas_UI_element.transform.position); 
    transform.position = Vector3.MoveTowards(StartPosition, DestinationPosition, MoveSpeed);
}

You haven't stated how it doesn't quite work, but that would perform the entire operation in world space. Have you tried the reverse: using WorldToScreenPoint to convert the cube's location to 2d screen space?

Apologies in my example the object moves to seemingly random points in world space when the camera moves. I swapped it as you suggested and again the destination point seems arbitrary, rather than smoothly on the canvas from where it started to the UI element. Perhaps I am approaching this in the wrong way?

2 Answers

2

I have finally come up with a solution that works. Here it is for anyone else that might have trouble doing this:

void FixedUpdate()
{
    //Get the location of the UI element you want the 3d onject to move towards
    Vector3 screenPoint = ui_element_gameobject.transform.position + new Vector3(0,0,5);  //the "+ new Vector3(0,0,5)" ensures that the object is so close to the camera you dont see it

    //find out where this is in world space
    Vector3 worldPos = Camera.main.ScreenToWorldPoint( screenPoint );

    //move towards the world space position
    transform.position = Vector3.MoveTowards(transform.position, worldPos, currentMoveSpeed);
}

without looking too much into it I'm not sure why the above works better than the original code, possibly that they were vector 2s

Works perfectly!

Im struggling with the same thing.
Were you able to figure out a solution for this?

The solution you have outlined simply moves my cube to another position, but not exactly to the UI element.

Yep the pasted is what im using. quite tricky for me to understand what your issue is from the description alone :/ you have code snippets or any more info?

heres info about everything that I've tried.... http://answers.unity3d.com/questions/1015433/move-3d-object-to-2d-canvas.html