- Home /
How to raycast using a vector3 and a rotation?
Hello everybody,
What I'm trying to do is to cast a ray, starting from the "feet" of my FPS-character controller, with a certain angle to the ground .
I want to make a "climbing constraint" using the method where if the casted ray encounters an obstacle ahead, then I can constraint the climbing of the character by tweeking the angle of the ray. I think this is standard procedure for what I aim to do.
However I can't figure out how to cast a ray using transform.forward and applying it a rotation in order to obtain the direction for my Physics.Raycast .
I have tried using Quaternion and no luck so far. What I'm curently doing is:
Quaternion rotation = Quaternion.Euler(0.0f,0.0f,45.0f);
Debug.DrawRay( collider.bounds.min,rotation * this.transform.forward * 400, Color.red);
I hope I'm not making this too confusing...
Please help and thanks in advance.
Answer by robertbu · May 25, 2013 at 09:07 PM
You want Quaternion.AngleAxis():
Quaternion rotation = Quaternion.AngleAxis (45.0f, transform.right);
Debug.DrawRay( collider.bounds.min,rotation * this.transform.forward * 4, Color.red);
Note I'm not sure exactly of the relationship of this ray to your object because your code creates a rotation around the 'z' axis. My visualization is that you want it to angle forward from the middle front of the character controller and go forward. If so, 'transform.right' is the axis you want to rotate around. Or if this is a 2D game and you are using transform.right for forward movement, then the axis would be transform.forward. Note for a 3D game, using the collider.bounds.min will not give you the point you expect for your feet.
Worked like you said, thank you kind sir.
I put -45° to have it the right angle, and you were right I needed the transform.right axis for my 3d game. You're also right for the collider.bounds.$$anonymous$$, it is slightly off. I will need to tweek it a little to have it right.
You could put an empty child game object at the feet, and use it for the position of the raycast.