- Home /
Move 3D object to 2D canvas
I am building the logic for the player to collect bonus points.
Whenever the bonus cube is tapped, I would like to move it towards the UIElement button.
I am struggling with the movement logic because I can't figure out what is the world co-ordinate of the UIElement button.
Using Unity GUI.
My Canvas -> has a Panel -> which has a smaller Panel --> which has a Button -> this is the UI Element you see in the image below.
I've tried a lot of things, including suggestions made on this similar post but it still does not move my 3D object exactly towards the 2D canvas. http://answers.unity3d.com/questions/968082/move-a-3d-object-from-world-space-in-the-camera-ui.html
I've tagged that button as "ResourceButton", then accessed it in my code like this:
Transform bonusPanel = GameObject.FindGameObjectWithTag("ResourceButton").transform;
Debug.Log (bonusPanel.position)
This simply gives me (0,0,0). So next I tried to do the ViewPort mapping.
Vector3 newPos = Camera.main.ViewportToWorldPoint(bonusPanel.position);
Now this gives me some co-ordinates that are just very close to my camera (31,27,17), but nowhere near the UI element that you see on the screen.
Vector3 newPos = Camera.main.ScreenToWorldPoint(bonusPanel.position);
THIS DIDN'T WORK EITHER. It just give me some co-ordinates that are just very close to my camera (31,27,17), but nowhere near the UI element that you see on the screen.
Any suggestions?
Answer by Major · Jul 27, 2015 at 03:21 AM
I am assuming that you want to smoothly move the object in question to the UI element, so you need a target to lerp to. So instead of messing with the cubes coordinates, I would mess with the UI element's coordinates. If you use ViewportToWorldPoint, and then use the Lerp function starting at the cubes coordinates and then moving to the transformed UI coordinates I think this would be the result you want.
Answer by Lomardii · Mar 23, 2016 at 03:11 PM
The question becomes more complicated if you have UI element (for example on right top corner) in Ortographic Camera with own zoom (for pixel perfect) and 3d object in another Perspective Camera (not ortogonalny to any world axis). I was trying to create Plane at place on which the Perspective Camera looking at and just raycast from screen point to that Plane:
Vector3 pos = coordinates.dueToCamera.ViewportToScreenPoint( new Vector3( 0.9f, 0.9f, 0f) );
Ray ray = Camera.main.ScreenPointToRay(pos);
float rayDistance;
Plane groundPlane = new Plane(Camera.main.transform.forward,
placeWhereTheCameraIsLookingAt);
if (groundPlane.Raycast(ray, out rayDistance)) {
my3dObjectMoveTowardsDestination = ray.GetPoint(rayDistance);
}
And in some way it works, even if the angel of main camera is changing. But the desitnation point is not perfect.