- Home /
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);
}
}
}
Answer by Owen-Reynolds · May 21, 2011 at 05:11 PM
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.
How could I integrate this into my code? But anyway, I guess I could just put the code on the camera.
In your update, you have a raycast (it goes left, from the gun?) Ins$$anonymous$$d, 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.
Your answer
Follow this Question
Related Questions
Making bullets go to the crosshair 1 Answer
GUI.button and onClick Terrain 2 Answers
Center of spherecast 0 Answers
Trouble targeting GUI with raycast 0 Answers
Center GUI.Label similar to GUIText? 2 Answers