# Collision detection: Triangle

Time：2020-10-26

## Introduction

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.

## Triangle/Point

This isSample page

Triangle and pointThe collision detection can be carried out from the angle of area. See the following figure: 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: ``````/**
*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 triangle`h`In 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;
}``````

## Recommend a lightweight but efficient free open source windows hotkey scripting language AutoHotKey

The words written in the front AutoHotKey is a lightweight, small but efficient, free and open source windows hotkey scripting language. Game manipulation, mouse operation, keyboard shortcut redefinition, shortcut phrases and so on, only you can’t imagine, without it, you can’t do it. The artifact of artifact, I hate to meet you late. install Download […]