- Home /
Projecting Oblique Screen Coords to Straight World Coords
I'm working on a game featuring a tilted perspective camera. For some purposes I must find the world coords of the mouse position but I want the returned world coords in a fixed height. Currently I'm using this code (pseudo)
ScreenToWorldPoint(mousePosition.x, mousePosition.y, nearClipPlane + distance)
As the camera is tilted, it returns different Y positions which ruins the output for me. Please take a look at the screenshot provided below and let me know how I can find the position that exactly matches the mouse position in the fixed height straight plane. (note: the game is perspective 3D, don't let the screenshot make it look like ortho 2D)
Thanks in advance!
P.S. Using raycasting is not an option, this should ideally work solely mathematically
Answer by troien · Nov 05, 2014 at 10:20 PM
If your 'ground' is a gameobject with a collider, you can simple raycast. Using Physics.Raycast
If your 'ground' is simply a fixed y position. Then the following piece of code should work if you add it to your Camera. (note that you should be pointing your camera at the ground though, otherwise the position inverts and ends up behind the camera)
using UnityEngine;
public class Example : MonoBehaviour
{
private void OnDrawGizmos()
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition); // This ray could be used for raycasting aswell
Vector3 positionOnFloor = ray.origin + (ray.direction * ((ray.origin.y - 0) / -ray.direction.y)); // the 0 in this calculation is the height (in world position) of your floor
Gizmos.DrawWireSphere(positionOnFloor, 1f); // As example, I draw a gizmo on the floor
}
}
Amazing, thank you so much for the fast response! If you have time could you please describe what's going on in the below line so I can learn? Thanks!
ray.origin + (ray.direction * ((ray.origin.y - 0) / -ray.direction.y));
I'm having problems with finding a good way to explain this. So I decided that I just make a image :p I hope this explains it.
Important thing to note: The direction is usually normalized. But not in this example because it makes calculating by head more difficult. Results would still be equal though so shouldn't be a problem.