Make an FPS gun point at the mouse position.

Hi,

Im new to unity and trying to make an on rails shooter, similar to time crysis or house of the dead. I also want the gun to be displayed on the screen but to point at where the mouse is, similar to how it does in red steel on the wii.

My problem is that I cant get the gun to reliability point at the cursor.

I found some usefull code HERE

private var targetPlane : Plane;

function Start(){
targetPlane = Plane(Vector3().up, 0);
}

function Update () {

var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var dist : float;
if(targetPlane.Raycast(ray, dist)){
var pos = ray.GetPoint(dist);
transform.LookAt(pos, Vector3().up);
}
}

This works well, except you cant point the gun up. So i changed Vector3().up to Vector3.().one. Now the gun can point in all directions, untill the camera faces back on itself from the starting position, when the gun will no longer follow the mouse at all.

Im using some code that I found HERE to move the camera from point to point, if its any help.

Ive been surching through the unity forums and pulling my hair out for best part of two days now. All Ive managed to figgure out is that Im 99% sure its something to do with where the plane is drawn and not being able to see it when the camra is rotated.

Thanks in advance!

Try using ScreenToWorldPoint:

var zDistance = 10.0;

function Update () {
    var mousePos = Input.mousePosition;
    transform.LookAt(Camera.main.ScreenToWorldPoint(Vector3(mousePos.x, mousePos.y, zDistance)));
}

What about if It’s a third person character an I have the gun parented to the character. It seems that the guns rotation starts off in the wrong rotation and isn’t following the target properly…