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
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;
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
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
– TinSleeves