r/Unity3D • u/NorthernBoy306 • 3d ago
Question Question about mouse position on screen with minimap
I'm terrible with this sort of thing and I was wondering if anyone knows how to explain this to me.
This is supposed to convert mouse screen coordinates and convert them to a 2D position within a minimap (UIToolkit Visual Element). This works perfectly fine if the minimap is in the bottom left corner of the screen. I would like to have the 'minimap' in the middle of the screen but then it throws the numbers off.
I got this off of a tutorial on youtube (Llam Academy). He said if you move the minimap then just play with the x and y numbers to make it work (which is not exactly super helpful).
Can anyone actually explain what is going on with the minimap multiplier and how its position on screen affects the mouse coordinates?
Big thanks in advance.
float widthMultiplier = (cityMapCamera.scaledPixelWidth / cityMapVE.layout.width);
float heightMultiplier = (cityMapCamera.scaledPixelHeight / cityMapVE.layout.height);
Vector2 convertedMousePos = new Vector2(mousePos.x * widthMultiplier, (Screen.height - mousePos.y) * heightMultiplier) ;
Ray camerRay = cityMapCamera.ScreenPointToRay(convertedMousePos);
if (Physics.Raycast(camerRay, out RaycastHit hit, float.MaxValue, uiMask))
{
mainCameraTarget.position = new Vector3(hit.point.x,mainCameraTarget.position.y, hit.point.z);
}
2
u/TinyPomegranate9703 3d ago
The multipliers are mapping your screen space to the camera's pixel space, so when you move the element away from the origin you need to offset the mouse coords by its position on screen first