- Home /
Setting exact Angle of a Raycast instead of using Direction
Hi everyone,
I am starting out using Raycasts but wanted to set a raycast that would check in a specific angle, instead of using the regular Vector3 directions like (Vector3.forward).
So something like:
float angleToCheck = 63f;
if( Physics.Raycast(transform.position, angleToCheck, out hit, 10f )
{
...
}
Obviously the above won't work as a Vector3 is required, but is there a way to represent the angle I am looking for as a vector3 that the raycast will accept? The angle needs to be relative to my gameobject, not the world.
For more background, this is a 2D game, so objects move along the X and Y axis not the Z (vector3.up or y-axis is the front of my objects).
Thanks!
Answer by Jesse Anders · Mar 29, 2011 at 10:32 AM
You can just build a vector corresponding to the angle, e.g. (untested):
direction = new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0f);
Depending on what convention you're using for your angles, you might need to swap and/or negate the first two arguments to the Vector3 constructor to get the right results.
Interesting, I'm trying this out but the raycast isn't pointing in the right direction. I think what I am missing is making the angle relative (local) to my gameobject.
So, say I have a gameobject rotated around the z axis at 45degress and I want to create a raycast at 20 degrees (in the z-axis) relative to the rotation of the gameobject. I've been playing with eulerangles but that doesn't seem to get me anywhere. Can I just add the gameobject's transform.position to this new direction?
First, make sure you're perfor$$anonymous$$g any degrees<->radians conversions as needed. Second, you can use the Transform functions TransformPoint(), InverseTransformPoint(), TransformDirection(), and InverseTransformDirection() to transform between local and world space. (TransformDirection() is probably what you want here.)
Thanks! I'll keep trying to figure it out, I guess I need to learn some of the basics of vectors, magnitude vectors to get to the bottom of this.
Your answer
Follow this Question
Related Questions
How to shoot raycast with slight random direction? 1 Answer
Raycast across angle? 3 Answers
How to add slight angle/rotation variation to transform.forward? 5 Answers
Raycast in the wrong way 3 Answers
Generate a random direction within min and max angles 2 Answers