- Home /
Problem is not reproducible or outdated
Get mouse location y relative to player position z
I'm trying to get the mouse y axis position on the screen from ScreenToWorldPoint but the problem is my camera is set to orthographic and has a angle of 25 on the x axis. I've setup a script to get the location of the mouse relative to the player and it works on the x axis but slowly goes out of sync on the y which I imagine is because of the camera angle as the player walks more and more up the screen?
Does anyone know how to get the mouse y location relative to the player position - the angle and height of the camera?
Answer by Ymrasu · Jan 31, 2019 at 09:42 PM
You are right that this is caused by the angle of the camera. ScreenToWorldPoint takes a ray from the camera to a point in the world a certain distance away (one of the parameters) but it is the same distance all the time, so it returns the y pos in world space taking that camera angle. What you want is a varying distance, since as objects higher in the y pos (according to the camera) are usually farther away.
To do this you need to cast your own rays out to a plane parallel to the world instead of the camera.
// make a plane in the world relative to the player (replace with your own variables)
Plane plane = new Plane(player.transform.up, player.transfrom.position);
// create a ray from your mouse
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// cast ray from mouse to the plane we made to get that varied distance mentioned earlier
if(plane.Raycast(ray, out float distance)) {
// get point in the world with that distance
var point = ray.GetPoint(distance);
}
That point should be the correct spot in world space where your mouse is, relative to the players z pos (since that is the how the plane was made).
Thanks this makes so much sense I will test tonight and see! I'll accept the answer after testing.
Follow this Question
Related Questions
Angle of object relative to transform of second object 2 Answers
Normalized Coordinates are Exponentially inccorect 2 Answers
How to get Ray rotation from direction 0 Answers
How to do relativte offset rotation 0 Answers
Finding Face Angle 0 Answers