- Home /
Rotated Camera fix for Screen to World point overshoots
I have a camera that rotates around on the x/y axis. I want to get player input and use the screen to world point to do it. This would be fine for a 3D game, as I could just use raycasts and everything would work as intended, but my game is 2D. I think I found a solution though. Heres the code
private static Vector3 GetScreenPoint()
{
Vector3 screenPoint = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
Vector3 screenPointZ = screenPoint;
screenPointZ.z = 0;
double distToZ0 = -screenPoint.z / Math.Cos(Vector3.Angle(Vector3.forward, Camera.main.transform.forward));
Vector3 point = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,(float)distToZ0));
Debug.DrawLine(screenPoint, point, Color.cyan);
Debug.DrawLine(point, new Vector3(point.x, point.y, 0), Color.red);
Debug.DrawLine(screenPoint,screenPointZ,Color.cyan);
Debug.DrawLine(screenPointZ, point, Color.cyan);
return point;
}
Hypothetically, this would return a point on the Z0 plane that matches up with my mouse cursor. But for some reason, it overshoots and goes past Z0, making my mouse cursor be significantly above where the actual selection is. Does anyone know why this is happening?
Your answer
Follow this Question
Related Questions
Project an object from a perspective camera at same screen position but different Y world position 0 Answers
Drag rigidbody with camera at angle? 0 Answers
Camera Screen to world point returns cameras transform position. 8 Answers
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
How can you access the Game screen and its properties from an Editor Script? 1 Answer