x


Raycasts hitting the crosshair

How could I make it so that raycasts always hit my crosshair in the middle of the screen? The script is on my gun which is to the right of me, so the raycast goes to the right.

var damage : float = 5;


function Update () {
    var direction = transform.TransformDirection(Vector3.left);
    var hit : RaycastHit;
    var localOffset = transform.position;

    if(Input.GetButtonDown("Fire1")){
       if (Physics.Raycast (localOffset, direction, hit, 400)) {
         Debug.DrawLine (localOffset, hit.point, Color.cyan);
         print("we have fired!");
         hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
       }
    }
}
more ▼

asked May 21 '11 at 06:46 AM

Max 4 gravatar image

Max 4
254 60 64 71

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

1 answer: sort newest

Look at camera.ScreenPointToRay( screenPixelPos ); for getting a good ray for the raycast. That gives you a straight down the screen ray.

I think you'd be better off ignoring the gun position for aiming, and just doing a straight raycast right down the center of the screen. You could then draw a line or something from the gun to the target, for effect.

Otherwise, you get a diagonal raycast (with respect to the screen) and the crosshair will only be correct for one paticular distance.

more ▼

answered May 21 '11 at 05:11 PM

Owen Reynolds gravatar image

Owen Reynolds
12.2k 1 7 46

How could I integrate this into my code? But anyway, I guess I could just put the code on the camera.

May 22 '11 at 01:56 AM Max 4

In your update, you have a raycast (it goes left, from the gun?) Instead, use a raycast directly out from the crosshair -- if the crosshair is over a duck, the raycast will hit it. Think of it as finding what's under the mouse (plenty of answers for that,) except the mouse is always in the same spot.

May 22 '11 at 02:19 AM Owen Reynolds
(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:

x3808
x1579
x92

asked: May 21 '11 at 06:46 AM

Seen: 1090 times

Last Updated: May 22 '11 at 02:19 AM