← Back to index

Point-in-triangle (barycentric)

Express the point as p = u·a + v·b + w·c where u + v + w = 1. The point lies inside the triangle iff all three weights are non-negative. The weights also tell you how to interpolate per-vertex data (colours, UVs, etc.) across the triangle.

See also: Point-in-circle — the corresponding hit test for a circular shape.

Pseudocode

denom = (b.y - c.y) * (a.x - c.x) + (c.x - b.x) * (a.y - c.y)
u = ((b.y - c.y) * (p.x - c.x) + (c.x - b.x) * (p.y - c.y)) / denom
v = ((c.y - a.y) * (p.x - c.x) + (a.x - c.x) * (p.y - c.y)) / denom
w = 1 - u - v
inside = u >= 0 && v >= 0 && w >= 0

Source

const ax = 60,  ay = 230
const bx = 240, by = 230
const cx = 150, cy = 50

const denom = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy)
const u = ((by - cy) * (mouseX - cx) + (cx - bx) * (mouseY - cy)) / denom
const v = ((cy - ay) * (mouseX - cx) + (ax - cx) * (mouseY - cy)) / denom
const w = 1 - u - v

const inside = u >= 0 && v >= 0 && w >= 0