raycast is not stable ?

Hello everyone, i have a raycast problem. Here is my code :

var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;


if (Physics.Raycast(transform.position, direction, hit)){

if (hitParticles) {
			hitParticles.transform.position = hit.point;
			hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
			hitParticles.Emit();
		}
		
		

}

Now my problem, this code is attached to the empty game object which stands in front of the scope, but when i fire it without moving the mouse, the particle is being emitted in two positions. For example, i’m firing it to the wall, there is y:30 point in the wall and y:25 point below it. Some of the fires goes to y:30 , some of it goes to y:25, which means my fire is not stable ,and also sometimes the particle is not even emitted, which means we don’t hit anything, what can be the problem ?

Thanks :).

1 Answer

1

Something in your scene is moving or rotating the object. If you’re aiming with the mouse, maybe some electrical noise is returning slight variations in the mouse axes around zero, which at a long distance becomes highly visible.

You can draw the ray with Debug.DrawRay to see if it’s really moving:

var direction = transform.forward; // this is an easier way to find the forward direction
var hit : RaycastHit; // draw a ray (click Gizmos in the game view to enable drawing)
Debug.DrawRay(transform.position, direction * 100, Color.red);
if (Physics.Raycast(transform.position, direction, hit)){
    if (hitParticles) {
         hitParticles.transform.position = hit.point;
         hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
         hitParticles.Emit();
    }
}

I tried what you said, and there were 2 red lines, one was static and from the point which is right, and the other one was from somewhere below and rotating till somewhere, then going to the same position it started ( it is somewhere below the gun ) and rotates again, any ideas ? ( and thanks)