- Home /
Coordinates of mouse in a box collider
Hello everyone !
I'm trying to make some UI : a texture with an alpha cutout handled by the position of the mouse in a box collider with the OnMouseDrag function.
But I don't know if it is possible to know what the mouse coordinates are, in the X-axis for example.
This may not be very clear :D If the user clicks on the mouse when it is into the bow collider, but totally on the left side, I want my alpha cutout at 0, on the middle at 0.5, and on the right at 1.
Answer by robertbu · Nov 16, 2013 at 05:07 AM
If your camera is axis aligned, and you know the world size of your object and your world object is not scaled, then calculating the relative x-axis is fairly straight forward. If your camera has a rotation of (0,0,0) and is therefore looking towards positive 'z', you can add a script like this to the object:
var pos = Input.mousePosition;
pos.z = transform.position.z - Camera.main.transform.position;
pos = Camera.main.ScreenToWorldPoint(pos);
pos = transform.InverseTransformPoint(pos);
'pos' is now in local coordinates. Negative values will be to the left, positive to the right. You can set a threshold for what you consider 'middle'.
Do you know how to do the same transformation with a second camera that is not moving and renders some UI while my FPS character is moving ? (the second camera renders some UI after the main camera)
EDIT : never$$anonymous$$d, I found it with exactly the same pattern of code, but entirely adapted for my second camera ...
Your answer
Follow this Question
Related Questions
Verify Planes collision inside OnMouseOver of another GameObject 0 Answers
How to change objects position a set number of units from it's current position? 0 Answers
ScreenToViewportPoint offset from Input.mousePosition ? 1 Answer
Detecting mouse position in 3d space. 1 Answer
Get mouse positon in world coordinates on a plane? 2 Answers