top of page
Search
cedarcantab

Understanding 2D Physics Engines with Phaser 3, Part 12: SAT - Polygon vs Line Collision Detection

Updated: May 23, 2023

This post will be short. It is about using the separating axis theorem (SAT) to detect collision between polygon and line segments.




Just to cement my understanding of the basic principle of SAT, I have amended the code from the previous post to detect collision between polygon and a line segment.


The basic principle behind SAT is to identify the existence (or not) of an axis that separates the two shapes being tested. If you know the possible axes, you loop through all those axes, projecting the vertices of the shapes onto those axes, to see if the "shadow" from the projection overlap. Very simple. The trick is to know which axes to test of the infinite number of potential axes.


In the case of polygons, the possible axes are the normals of the faces (edges) of the polygons.


In the case of a line segment, you can consider it as a very thin polygon and take the axes as the following:

  1. normalized version of the segment itself

  2. a unit vector perpendicular to itself


I have created a getAxes method for a new Line Segment class as follows.


getAxes() {
    
    let axes = [];
    const axis1 = new Phaser.Math.Vector2(this.x2-this.x1, this.y2-this.y1)
    const axis2 = new Phaser.Math.Vector2(this.x2-this.x1, this.y2-this.y1).normalizeLeftHand().normalize();
    axes.push(axis1, axis2);
    return axes;
    
  }

The logic for the actual SAT is exactly the same as described in the previous post.



CodePen



Comments


記事: Blog2_Post
bottom of page