- Home /
How to draw a circle around a moving game object
I made a function to draw a circle around a given position, with a given radius:
// Draw circle on XZ plane
private void DrawCircle(Vector3 position, float radius)
{
var increment = 10;
for (int angle = 0; angle < 360; angle = angle + increment)
{
var heading = Vector3.forward - position;
var direction = heading / heading.magnitude;
var point = Quaternion.Euler(0, angle, 0) * (position + direction * radius);
var point2 = Quaternion.Euler(0, angle + increment, 0) * (position + direction * radius);
Debug.DrawLine(point, point2, Color.red);
}
}
However, this circle gets drawn around the origin 0,0 instead. Can someone tell me what I'm doing wrong, also links to any resources would be great. Thanks!
Answer by Bunny83 · Jan 18, 2020 at 06:33 PM
Well, your code doesn't make much sense to me. First of all your "heading" value doesn't seem to contain any meaningful value. You essentially mirror your position vector to the other side around the world origin and add 1 to the z component. So it's a position just on the other side of the origin. You then normalize that direction.
Next you multiply that unit vector by your radius and again add your position. Finally you rotate that position around the world origin. I guess you wanted to do something like this:
var point = position + Quaternion.Euler(0, angle, 0) * Vector3.forward * radius;
var point2 = position + Quaternion.Euler(0, angle + increment, 0) * Vector3.forward * radius;
Though since Debug.DrawLine only has an effect inside the editor, you could simply use Handles.DrawWireDisc. However DrawWireDisc can only be called from a rendering callback. For example in OnDrawGizmos / OnDrawGizmosSelected, OnGUI, OnSceneGUI, ... Without more context it's not clear when or for what you need this circle-
Thank you for your explanation, I will try this. I know other drawing methods exist, but this question was to help with my understanding of vectors and rotations
Your answer
Follow this Question
Related Questions
Positions to rotations of a regular GO 2 Answers
How to determine if rotation is clockwise or anticlockwise 2 Answers
Trouble with Camera Rotation Math 2 Answers
Function to rotate my Player smoothly taking the y and use it to have angle 1 Answer
How to find or compute or look for overall/max RPM by simply checking for rotation? 1 Answer