Skip to content

Javascript implementation of the Separating Axis Theorem for convex polygons and polyhedra

Notifications You must be signed in to change notification settings

pboechat/SAT.js

Repository files navigation

SAT.js

SAT.js is a Javascript implementation of the Separating Axis Theorem for convex polygons and polyhedra.

Requires three.js.

Based on this article.


Usage

Add three.js and SAT.js to your page:

<script type="text/javascript" src="three.js"></script>
<script type="text/javascript" src="SAT.js"></script>

Polygons

With the vertices of your polygon, construct a SAT.Polygon:

var polyA = new SAT.Polygon([new THREE.Vector2(-0.5, -0.5), 
new THREE.Vector2(0.5, -0.5),
new THREE.Vector2(0.5, 0.5),
new THREE.Vector2(-0.5, 0.5),
]);
var polyB = new SAT.Polygon(verticesB);

Notice that the vertices must be in counter-clockwise order.

Polyhedra

With the vertices, edges and faces of your polyhedron, construct a SAT.Shape:

// 1x1x1 cube centered in origin
var polyA = new SAT.Shape(
// vertices
[
	new THREE.Vector3(-0.5, 0.5, 0.5), new THREE.Vector3(-0.5, -0.5, 0.5),
	new THREE.Vector3(0.5, -0.5, 0.5), new THREE.Vector3(0.5, 0.5, 0.5),
	new THREE.Vector3(0.5, 0.5, -0.5), new THREE.Vector3(0.5, -0.5, -0.5),
	new THREE.Vector3(-0.5, -0.5, -0.5), new THREE.Vector3(-0.5, 0.5, -0.5),
],
// edges
[
	[0, 1], 
	[1, 2], 
	[2, 3], 
	[3, 0],
    [4, 5], 
    [5, 6], 
    [6, 7], 
    [7, 4],
    [3, 4], 
    [2, 5], 
    [0, 7], 
    [1, 6]
],
// faces
[
    [0, 1, 2, 3],  // front
    [4, 5, 6, 7],  // back
    [3, 2, 5, 4],  // right
    [7, 6, 1, 0],  // left
    [7, 0, 3, 4],  // top
    [5, 2, 1, 6]   // bottom
]);
var polyB = new SAT.Shape(verticesB, edgesB, facesB);

Your faces must reference your vertices in counter-clockwise order.

Collision Checking

SAT.CheckCollision(polyA, polyB)

Demo

Examine the SAT algorithm step-by-step here.


Video

Video

About

Javascript implementation of the Separating Axis Theorem for convex polygons and polyhedra

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published