- Home /
Same RayCast is returning different hit points
Hello all. I'm making a third-person shooter game, and I'm using Physics.Raycast to act as a hitscan for my guns. However, when I added a laser sight to my gun, I noticed that some shots weren't aligned with the laser (debris prefab was spawning a little below where it should). After logging the hit point of my raycast, I saw that it was the Raycast function that was returning different points even though the position and direction of the ray never changed. This could potentially be a big problem, as my game is about stealth and precision.
Here is my code:
public float FireRate = 0.1f;
public float RechamberTime = 0.1f;
public float Damage = 25.0f;
float CurrentClip;
float ClipSelected = 1;
public float Clip1 = 30f;
public float Clip2 = 30f;
public float Clip3 = 30f;
public float Range = 100;
public GameObject CameraPosition;
public AudioClip Shot;
RaycastHit HitInfo;
if (RechamberTime <= 0 && CurrentClip > 0 && Input.GetMouseButton (0)) {
RechamberTime = FireRate;
audio.PlayOneShot(Shot);
if (ClipSelected == 1) {
Clip1 -= 1;
}
if (ClipSelected == 2) {
Clip2 -= 1;
}
if (ClipSelected == 3) {
Clip3 -= 1;
}
Debug.Log ("Bullets Left: " + CurrentClip);
//Hitscan by casting Ray
Ray Aim = new Ray (this.gameObject.transform.position, this.gameObject.transform.forward);
if (Physics.Raycast (Aim, out HitInfo, Range)) {
Vector3 HitPoint = HitInfo.point;
GameObject Target = HitInfo.collider.gameObject;
Debug.Log ("HitObject: " + Target.name);
Debug.Log ("Hit Point: " + HitPoint);
Health TargetHasHP = Target.GetComponent<Health> ();
if (TargetHasHP != null) {
TargetHasHP.TakeDamage (Damage);
}
//Spawn prefab
Shootable DebrisAttatched = Target.GetComponent<Shootable> ();
if (DebrisAttatched != null) {
DebrisAttatched.SpawnPrefab (HitPoint);
}
}
Sorry for the long block of code, but I've scoured it over and over and can't find anything wrong. I followed a tutorial by quill18creates on YouTube to the letter, so you can imagine my frustration. ^^;
Answer by DJT4NN3R · Mar 30, 2014 at 01:24 AM
The laser sight is a line renderer component attached to the gun. It draws a line originating from the barrel of the gun and travels 1000 units forward.
I'm pretty sure the raycast ISN'T the problem. I followed a YouTube tutorial to the letter in order to set it up.
As far as testing it on another object, I placed two cubes on top of each other and gave them both colliders, and it did the same thing. I don't see how anything else could be moving or rotating, considering that there's no references to anything other than the Sparks prefab and the gun itself, and neither of those references says anything about moving or rotating...
I'll triple check the tutorial and see if I did anything wrong as far a setting up the scene, because I'm almost 100% sure there's nothing wrong with the script...
EDIT
Okay, so I've discovered the problem and fixed it. I had a RigidBody component attatched to my Player object, and it had gravity checked. I disabled gravity and it works. I'm not quite sure why this would be causing a problem because my player object ALSO had a character controller attached (which comes standard with a capsule collider),and if gravity was causing the gun to move, and gravity is a downward force, and the gun was attached to the object with a collider that was supposed to STOP gravity from acting on the object, then why would gravity be pulling things down that were already on the ground? Anyways, thanks for your advice, guys. I appreciate you all taking the time to help.
What gameObject is the raycast script on? For a good test, put it on an empty, or a capsule. Otherwise it could be getting moved by some other script, animation, jittery physics... .
I attached all the same components (Line renderer, Gun script, Audio source; copy and pasted) to a 0.1 x 0.1 x 2 cube object, then disabled all the components of the old gun, and the Raycasts are still perfor$$anonymous$$g the same way. I even set up my player so that I was facing a wall on the spawn so I wouldn't have to turn at all to shoot, and it does the same thing.
Okay guys, I've made a breakthrough. In my original setup, the gun was a child of the an empty object called Player, as well as the model and the camera position. I de-parented the gun and it shoots straight. So, the problem obviously lies within the empty player object.
I logged the position of the gun each shot, and apparently the gun is moving along the Y axis when it shoots. So, combined with my previous discovery, this leads me to believe that the player object is influencing it to move somehow.
characterControllers vs. rigid bodies are a common topic here. There are alternate ways to move something. If you use both on the same object, they both move it, giving odd results.
Answer by Owen-Reynolds · Mar 28, 2014 at 04:19 PM
Don't think it's the script. The key line is exactly perfect, Line 33: Ray Aim = new Ray (transform.position, transform.forward);
(this.gameObject is redundant.)
That fires directly from whatever the script is on, directly the way it's aiming. If the script is on the +Z business end of the gun, this is exactly where the little blue arrow on the gun is aimed.
Something in the scene is set up wrong. Maybe the gun is centered too low (so the blue line comes out below the barrel.) Maybe the laser is aimed funny. Or maybe aim is fine but the debris prefab drops too quickly. Or this script is on the arm, and not the slightly angled gun... . I'd make a tiny red cube, no collider, and put testCube.position = HitPoint
after line 35. Should show the problem better.
No, I've Debug.Log()'d the HitPoint in line 38 and it actually returns different points. There's no pattern either; I've fired all 30 shots of BOTH clips and I can never predict which shots will stray off. :/
Are you sure your debris prefab doesn't have some colliders? keep in $$anonymous$$d the ray could hit any collider, even triggers unless the collider is in the "IgnoreRaycast" layer. You log the name of the object you hit, have you checked that you hit the correct object? Is the name unique?
You said it returns "different" points, how much different? Are you sure you and / or the target do not move / rotate?
I'm using raycasts quite often and they always behaved like they should. It has to be something else.
Where does your laser sight start? it can't really start at the same position as your barrel or does it?
$$anonymous$$y debris prefab has no colliders. It's the standard assets particle called "Sparks" under "Particles\$$anonymous$$isc". The only non-default component attached is a script that makes it destroy itself after 0.5s.
I've logged the object I hit and it returns the right object, and yes, the name is unique.
Each point returned by the RayCastHit is (I actually just discovered this) LOWER than the last point. It gives an effect as though I was moving my aim down, but my aim isn't moving at all. I've fired the gun directly at the wall without moving or rotating myself OR the camera, and it still hits different places.
If by "laser sight", you mean Ray Aim (Line 33), then the ray starts at the origin of the gun. I've centered the gun perfectly in Blender, and the gun has no collider.
I'll try to post a video to YouTube to show what I'm talking about. It's really beginning to make me angry, but I'm sure there's a solution.
In your question, you wrote you "added a laser sight". I/We assumed that means some other script is drawing a visible line or dot at the aim point. By "laser sight," you just mean "using a raycast to hit"?
$$anonymous$$oving the camera shouldn't matter, since this ray doesn't look at where the camera is. It compares world gun to world target. A wrongly-aligned Blender model won't make the hitPoint keep changing. If would ins$$anonymous$$d be wrong the same amount each shot.
$$anonymous$$aybe try printing, each shot, your position, rotation and target pos? And commenting out the clip stuff, so testing is easier? Is there an animation anywhere? Raycasts are just math, and I've never seen two give different results w/everything in the same place.
Try your script in a new scene, shooting from a fixed cube into another cube. Then bring in the thing you're shooting at now. If hitPoint doens't more there, it means the raycast isn't the problem.
Your answer
![](https://koobas.hobune.stream/wayback/20220613141407im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
iam using raycast.hit function.am trying to move vehicle over the terrain ups and down?? 0 Answers
RaycastHit2D How to return angle from one side? 2 Answers
Findout if an object that was hit by raycast is still being hit (30 object that are instantiated) 0 Answers
Double Score Problem ? 1 Answer
Points system doesn't work 0 Answers