raycasthit.normal sometimes returns zero
Hello, so here is my story, my "player" shoots a blast, the "blast" object has a trigger and when it is shot and hits an object with tag "enemy", it adds a force to the object relative to the normal of the hit.
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "enemy")
{
RaycastHit hit;
Physics.Raycast(transform.position, col.gameObject.transform.position,
out hit, DistanceToEnemy(col.gameObject));
Debug.Log("Distance To Enemy: " + DistanceToEnemy(col.gameObject));
col.gameObject.GetComponent<GetHitEvent>().GetHitEffect(gameObject, hit.normal);
Destroy(gameObject);
}
}
and here is the GetHitEffect(GameObject, Vector3) function code
public void GetHitEffect(GameObject blastObj, Vector3 hitAngleVector) //hitAngleVector is the hit.normal
{
GetComponent<Rigidbody>().freezeRotation = false;
GetComponent<Rigidbody>().AddForce(-hitAngleVector * 6, ForceMode.Impulse);
}
so my problem is that when i fire a blast object and it hits the enemy, sometimes, the hit.normal is zero and i get no force on the object, but other times it calculates the hit perfectly fine.
your help is immensely appreciated.
Answer by Johan-Ed · Jun 06, 2018 at 06:59 PM
I think I see a flaw in your code. You use Physics.Raycast and the second parameter of the method you have chosen is direction. The vector between the bullet and the enemy is given by:
col.transform.position - transform.position
If you want to raycast from your bullet to your enemy, this should be your direction (second parameter).
.
The (potential) error aside, I had the same problem, the Raycast hit had a normal of (0, 0). The only case I know of where this is correct, is if the Raycast in fact hit nothing.
.
Like me, you use OnTriggerEnter to verify a collision before you throw a Raycast, and because of this (and also like me) you dont really have to check whether the raycast hit anything, because you know there is something there.
However if your direction is off, or if the raycast is too short, you might miss the collider you were shooting for. If this happens and you don't verify that you actually hit, then you might end up with a very confusing hit.normal = (0, 0) / (0, 0, 0).
.
In my case it turned out my math was bad and the length of my raycast was (at a specific angle) not long enough, causing no Raycast hit 1/100 times.
Your answer
Follow this Question
Related Questions
A cube, raycasthit and rotation 0 Answers
hit normal vector from raycast is always [-1,0], which makes slope angle 90 1 Answer
RayCast2D and RayDraw errors 0 Answers
raycast : get normal value of linecast hit 1 Answer
Raycast Getting Caught 0 Answers