Jump to content

(Answered) How to get on-screen coordinates of object?


Recommended Posts

I need to get the on-screen x,y coordinates of an object.  Right now it's a toolbar button, but later other stuff.

So for now, talking about ApplicationLauncherButton, I get the button when it's clicked.  But so far, I haven't been able to find anything (transforms, etc) which are remotely close to what the onscreen location is.  I know the approximate onscreen location from the mouse, I can get the mouse location using Input.mousePosition, and the Vector3 which is returned gives the x,y location.

I've tried using the following, with no success:

  • button.sprite.transform.position
  • button.position
  • button.GetAnchor()
  • button.GetAnchorTopRight()
  • button.GetAnchorUL()
  • button.GetAnchorUR()

 

button.transform.position doesn't give anything close.

Suggestions?

 

Edited by linuxgurugamer
Link to comment
Share on other sites

2 hours ago, Thomas P. said:

Looked promising, but no go.

So, I use the following code to get the correct camera:

Camera cam;

if (HighLogic.LoadedSceneIsEditor)
    cam = EditorLogic.fetch.editorCamera;
else if (HighLogic.LoadedSceneIsFlight)
    cam = FlightCamera.fetch.mainCamera;
else
    cam = Camera.main;

and then this:

 Vector3 screenPos = camera.WorldToScreenPoint(button.transform.position);
 Debug.Log("target location is " + screenPos.x.ToString() + ", " + screenPos.y.ToString());

var mouse = Input.mousePosition;
Debug.Log("mouse  position: " + mouse.x.ToString() + ", " + mouse.y.ToString() + ", " + mouse.z.ToString());

button is set when I add the button to the app toolbar.

and the values I get are nowhere near what the mouse position is:

mouse  position: 1477, 25, 0
location is 313.2482, -684.1502

The mouse is on top of the button when I click it, and at that moment I get the coordinates

Link to comment
Share on other sites

That works for any transform, the key is finding the right camera. For a part it would be the flight or editor camera depending on the scene, for a map node it would be the planetarium camera, and, as you found out, for most UI elements you can get the camera from the relevant canvas.

Link to comment
Share on other sites

This thread is quite old. Please consider starting a new thread rather than reviving this one.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...