- Home /
Perspective top down laser.
I've been designing a game but I've hit a snag. I want a perspective camera because it fits the style better, and the camera's at a 45°, which makes it hard to get a laser working. [See figure 1.]
I want the laser to be fired from the players head through a point at y = 2, and through the mouse pointer. [See figure 1.]
So far, I've come up with firing a raycast from the mouse to the floor, getting the distance, using the sin rule with the angle from the mouse to the camera and height 2, to get the hypotenuse of the right angled triangle, taking that from the distance between floor and angle, and moving an empty to that distance away from the mouse, then just getting the player to look at that point, firing a raycast, and drawing a line between the hit point and the player head. [See figure 2.]
I'm not looking for code, I was just wondering if there's an easier way of doing it?
Thanks, David :)
Answer by robertbu · Nov 06, 2013 at 07:29 PM
A typical way to solve this problem is to use Unity's mathematical Plane class. The plane is constructed at the position of your character using the world's up vector. You would construct a ray from the mouse position and use Plane.Raycast() to get the point. It will look something like (untested).
var plane = new Plane(transform.position, Vector3.up);
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var dist : float;
plane.Raycast(ray, dist);
var point = ray.GetPoint(dist);
var laserDirection = point - transform.position;
Thanks, that's amazing :)
Another thing I was thinking of doing was having a second (invisible) floor and firing a raycast into that, but then I ran into problems with collisions and rigidbodies. This fixes that perfectly :D