- Home /
Raycasting, rotating a ray 360 degrees
I've looked but couldn't find an answer to this question so apologies if its already been answered before and I missed it!
I'm working on a 2D game and basically I want to cast a ray and have that ray rotate 360 to check if it touches the player. Hopefully this image will make it obvious what I'm talking about
I know how to cast rays and check for collision like this:
void ShootRay()
{
origin1 = transform.position;
RaycastHit hit;
if (Physics.Raycast(origin1, direction, out hit))
{
Debug.DrawLine(transform.position, hit.point, Color.green);
}
}
I just can't for the life of me get this thing to rotate, so any help would be great
Thanks
Answer by robertbu · Apr 11, 2013 at 11:33 PM
I can think of three ways off the top of my head. I don't know which is the most efficient way (or if efficiency is a concern). One simple way is to use a polar to rectangular conversion. Assuming the above is on the x,y plane and 0 on the z axis, you can construction your your direction like:
Vector3 direction = new Vector3(Cos(angle), Sin(angle), 0);
'angle' needs to be in radians. If you are working with degrees in your for loop, you can use Mathf.Deg2Rad to make the conversion.
Another way would be to rotate the object this script is attached to (or an empty game object). Again assuming the x,y plane, you can do:
transform.Rotate(0.0f, 0.0f, delta_degree).
direction = transform.up;
Transform.Rotate() does an incremental rotation.
The third way use Quaternion.AngleAxis().
Quaternion q = Quaternion.AngleAxis(delta_degree, Vector3.forward);
direction = Vector3.up;
Each time you want to increment the angle, do:
direction = q * direction;
This code rotates the direction vector by delta_degree degrees each time it is executed.
Wow thanks for the detailed answer, all three suggestions were extremely helpful. I went with the third method in the end because it seemed to suit my situation best.
Thanks again
Answer by mmk · Nov 12, 2015 at 04:24 PM
For any one else looking i was trying this and to rotate around i did this,
Quaternion q = Quaternion.AngleAxis(100*Time.time, Vector3.up);
Vector3 d = transform.forward *20;
Debug.DrawRay (transform.position,q*d,Color.green);
Your answer
Follow this Question
Related Questions
How can i follow an object by 1-axis-rotation? 0 Answers
Rotation for 180 degrees of character 1 Answer
raycast to determine pivot 1 Answer
Make an object translate/raycast a certain way disregarding it's rotation 1 Answer
How can i rotate the aircraft elevator around the yellow axis up and down ?? as shown in the pic 0 Answers