bevy_gizmos/primitives/helpers.rs
1use core::f32::consts::TAU;
2
3use bevy_math::{ops, Vec2};
4
5/// Calculates the `nth` coordinate of a circle.
6///
7/// Given a circle's radius and its resolution, this function computes the position
8/// of the `nth` point along the circumference of the circle. The rotation starts at `(0.0, radius)`
9/// and proceeds counter-clockwise.
10pub(crate) fn single_circle_coordinate(radius: f32, resolution: u32, nth_point: u32) -> Vec2 {
11 let angle = nth_point as f32 * TAU / resolution as f32;
12 let (x, y) = ops::sin_cos(angle);
13 Vec2::new(x, y) * radius
14}
15
16/// Generates an iterator over the coordinates of a circle.
17///
18/// The coordinates form an open circle, meaning the first and last points aren't the same.
19///
20/// This function creates an iterator that yields the positions of points approximating a
21/// circle with the given radius, divided into linear segments. The iterator produces `resolution`
22/// number of points.
23pub(crate) fn circle_coordinates(radius: f32, resolution: u32) -> impl Iterator<Item = Vec2> {
24 (0..)
25 .map(move |p| single_circle_coordinate(radius, resolution, p))
26 .take(resolution as usize)
27}
28
29/// Generates an iterator over the coordinates of a circle.
30///
31/// The coordinates form a closed circle, meaning the first and last points are the same.
32///
33/// This function creates an iterator that yields the positions of points approximating a
34/// circle with the given radius, divided into linear segments. The iterator produces `resolution`
35/// number of points.
36pub(crate) fn circle_coordinates_closed(
37 radius: f32,
38 resolution: u32,
39) -> impl Iterator<Item = Vec2> {
40 circle_coordinates(radius, resolution).chain(core::iter::once(single_circle_coordinate(
41 radius, resolution, resolution,
42 )))
43}