Collision detection: Triangle



stayCollision Detection :PolygonThis paper mainly introduces the polygon related collision detection, and then look at the situation of triangles. Triangles also belong to polygons, so polygon method is applicable to triangles. Here’s another way of thinking.

The following examples are not checked for compatibility and are recommended to be viewed in the latest chrome browsers.


This isSample page

Triangle and pointThe collision detection can be carried out from the angle of area. See the following figure:

Collision detection: Triangle

If the point is in the triangle, then it is connected with the vertex of the triangle and cut into three parts. If the sum of the areas of these three parts is equal to the area of the triangle, then it can indicate that a collision has occurred.

To calculate the area of a triangle, you can useCross productandHelen’s formula:

Collision detection: Triangle

 *The cross product is represented by the symbol X
 *V vector
 *W vector
 *The modulus of the vector|v|||w| is the actual length of the line segment
 *Angle between θ V and W

V x W = |V| * |W| * sin(θ)

 *Formula for calculating area
 *A bottom
 *H high
S = a * h * 1/2

As you can see from the figure above|W| * sin(θ)The result is the height of the trianglehIn other words:

S = a * h * 1/2 = V x W *1/2

Based on the above theoretical support, the following is the complete detection logic:

 *The coordinates of triangle vertex in the form of [[x1, Y1], [X2, Y2]]
 *(PX, py) detection point coordinates
function checkTrianglePoint({points,px,py}) {
  const [point1,point2,point3] = points;
  const [x1,y1] = point1;
  const [x2,y2] = point2;
  const [x3,y3] = point3;
  //Original gross area
  const areaOrig = Math.abs( (x2-x1)*(y3-y1) - (x3-x1)*(y2-y1) );

  //Area formed by detection point and triangle vertex
  const area1 = Math.abs( (x1-px)*(y2-py) - (x2-px)*(y1-py) );
  const area2 = Math.abs( (x2-px)*(y3-py) - (x3-px)*(y2-py) );
  const area3 = Math.abs( (x3-px)*(y1-py) - (x1-px)*(y3-py) );
  const areaTotal = area1 + area2 + area3;

  //Allowable value of calculation error
  const buffer = 0.1;
  if (areaTotal >= areaOrig-buffer && areaTotal<= areaOrig+buffer) {
    return true;
  return false;

reference material

Recommended Today

Choose react or angular 2

Original addressChoosing between React vs. Angular 2The following is the translation of this article, which can be used at your choiceReactperhapsAngular2We need to help when we need to. React has become a cool representative in 2015, but angular.js has changed from a front-end framework that people love to a terrible devil (and not so terrible…) […]