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)
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
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
}
}