- Home /
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
can someone help me with this, thanks
Answer by robertbu · Mar 30, 2013 at 07:12 PM
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.
thanks, it works perfect, i appreciate your observations and i'll try to improve the code
Your answer
![](https://koobas.hobune.stream/wayback/20220613095400im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
RaycastAll isn't finding all possible collisions 1 Answer
Limiting RotateTowards on two axes 1 Answer
Locking onto enemies with the third person controller 2 Answers
How can I make my gameObject find the nearest object with a specific tag and rotate to look at it? 6 Answers
Rotate object without rotating RayCast 4 Answers