I’m having some trouble with this:
I’ve got a cursor being drawn in my GUI layer. It’s being driven by mouse movement, but it doesn’t always match the mouse position on the screen.
I’d like to see what this home-made cursor is hovering over in my scene, so I figure I’ll cast a ray into the scene from my cursor position. I figure the first step to do that is to convert my cursor position from Screen Space or Viewport Space into World space, but that’s where I run into trouble.
any attempts to convert my SS or VS position into a WS position, ie:
print(camera.ScreenToWorldPoint(cursorPositionSS));
// or:
print(camera.ViewportToWorldPoint(cursorPositionVS));
…just returns my camera’s WS position, even though my cursor’s position is not in the center of the screen (and therefore offset from the camera’s origin?). What am I missing here, and is there a common way to raycast into a scene from a cursor position?
Thanks a lot for any help!
Orion
/redacted/ (thought I had found a solution, but I had not). Any help would be much appreciated, although I’m still looking…
To answer your first question about why the world position is always the camera’s position, it’s due to the lack of a Z value in the vector. Both ScreenToWorldPoint and ViewportToWorldPoint rely on the Z value to determine how far away from the camera to calculate the resulting world space position. Therefore, if Z is 0, the world space position will always be the camera’s position.
As for getting an object that’s on the GUILayer to match the mouse’s position on screen, I would suggest the following approach…
Since your mouse position is in screen space (pixels) and GUI Layer positions are in Viewport space, simply set the position of the GUI object using the following…
cursorObject.transform.position = camera.ScreenToViewportPoint(Input.mousePosition);
colin, thanks a lot for the help! On the first point- ah, ok. That makes a lot of sense. For the second- that’s not exactly what I meant. Lemme word it differently-
I don’t want to match a GUI object’s position with the mouse position. I’ve made my own custom cursor (a GUI Object), and hidden/locked the mouse cursor. My custom cursor doesn’t always match up with the mouse input (you can disable it, and still be changing the mouse position), but I still want to be able to ‘click’ objects in the scene with it based on it’s SS position.
So I’ve got a custom cursor, completely separate from the mouse position, and I want to cast a ray from it’s SS position into the scene, to see what it hits. What would be a good way to do this?
Thanks again!
I’m not sure why your not getting the correct results with ScreenToWorldPoint, but for what your intended to do its not need - ScreenPointToRay will do all the dirty work for you 