Problem with the direction of the raycast when rotating

I have character who rotate over itself, it has attached a gun which has attached an empty gameobject in front of the cannon that i use for instantiate bullets and start the raycast, the problem is when the character rotate the raycast still pointing to the first direction but in some point the ray rotate 90 degrees in the direction that was rotating

camera = the main camera

cannon = the empty gameobject attached to the gun

target = the direction of the bullets

Vector3 direction = cannon.transform.forward;
RaycastHit hit = new RaycastHit();
Ray ray = new Ray(cannon.transform.position, direction);
if(Physics.Raycast(ray, out hit))
{
    Debug.DrawLine(cannon.transform.position, hit.transform.position);
				
    camera.transform.LookAt(hit.transform.position);
    target = Vector3.Normalize(hit.transform.position - cannon.transform.position);
}
else
{
    camera.transform.LookAt(laserEnd.transform.position);
    target = Vector3.Normalize(laserEnd.transform.position - cannon.transform.position);
}

when the game start

when rotate the character

when rotate a little more
alt text

can someone help me with this, thanks

I believe your problems is that you are using “hit.transform.position” rather than “hit.point”. That is, the ray is finding the center point of the object hit (i.e. the wall), rather than the point found by the raycast. So replace your hit.transform.position statements with hit.point. A couple of ther observatons:

  • You don’t need to create a new RaysastHit as you do on line 2.
  • I’m not sure how you are using ‘target’, but you probably don’t need to normalize it.