x


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!

more ▼

asked Mar 04 '10 at 05:47 PM

orv gravatar image

orv
29 2 4 7

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Try using ScreenToWorldPoint:

var zDistance = 10.0;

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

answered Mar 04 '10 at 08:39 PM

Eric5h5 gravatar image

Eric5h5
80.1k 41 132 519

Yep, that it it. Thanks very much!

Mar 05 '10 at 11:53 AM orv

Quick question... I am trying to use this method to achieve something similar (if not the same thing). Basically, I'm trying to get a gun to point at the cursor, however, when I use this method it feels like the gun isn't pointing at the cursor directly all the time especially as it moves from the 'center' of the screen. It feels like it has to be scaled to fit the screen or something. Is this normal and if so how do you fix this?

Dec 21 '10 at 09:48 PM jeanRicK

@jeanRicK: try setting zDistance to different values.

Dec 21 '10 at 10:52 PM Eric5h5
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5057
x573
x327
x195

asked: Mar 04 '10 at 05:47 PM

Seen: 4303 times

Last Updated: Mar 04 '10 at 05:47 PM