sepax2d
A safe Rust crate for finding and resolving collisions of convex shapes using the Separating Axis Theorem (SAT) in two dimensions.
Usage
Add the following to the [dependencies] section of your Cargo.toml:
= "0.3"
Import the types of shapes you'd like to use and create some new shapes:
use *;
let rectangle = AABBnew;
let circle = new;
let capsule = new;
//The vertices of a polygon are position vectors
//relative to the shape's position, i.e. if position
//is (1, 2), then the absolute location of the
//first vertex is (1, 0).
let triangle = from_vertices
;
Use the sat_overlap(&left, &right) method to get a bool indicating whether or not the two given shapes overlap.
Any struct implementing the Shape trait can be used.
assert!;
assert!;
Use the sat_collision(&left, &right) method to get a (f32, f32) which represents the shift needed to add to right's
position in order to resolve the overlap of the two shapes.
let resolution = sat_overlap;
let position = triangle.position;
triangle.set_position;
assert!;
Use the contains_point(&shape, point) method to get a bool indicating whether or not the specified point
is inside the given shape.
let rectangle = AABBnew;
assert!;
assert!;
Considerations
The Separating Axis Theorem only holds for convex shapes. If a concave shape is passed in, it is possible for overlap to be missed and false overlap to be detected.
Convexity is not a problem for Circle, AABB, or Capsule as those are convex by definition. For
polygons, it is possible to define a concave shape. Polygon convexity can be tested using the
polygon.is_convex() method. Alternatively, the Polygon::convex_from_vertices(position, vertices)
constructor returns an Option(Polygon), which is None if you try to make a concave polygon.
Examples
The repository includes two example applications built with ggez which show off the overlap and collision functionality. They can be run from the repo via:
Contribution
Please feel free to suggest additional features, bug fixes, or optimizations. Thanks!