Skip to main content

centroid: Triangle Geometric Center Calculation

Arithmetic Mean Method for Triangle Center Point

The triangle centroid function computes the geometric center of a triangle by calculating the arithmetic mean of its three vertices. This fundamental operation determines the balance point where the triangle would rest if made of uniform material.

Given triangle vertices AA, BB, and CC, the centroid formula is:

Centroid=A+B+C3\text{Centroid} = \frac{A + B + C}{3}

This simple averaging operation produces the point equidistant from all three vertices in terms of their vector sum. The centroid divides each median line (line from vertex to opposite edge midpoint) in a 2:1 ratio.

Live Editor
const fragment = () => Scope(() => {
      const time = iTime.mul(0.3)
      const tri = Triangle({
              a: vec3(-0.5, -0.3, 0),
              b: vec3(0.5, -0.3, 0),
              c: vec3(time.sin().mul(0.3), 0.4, 0)
      })
      const center = triangleCentroid(tri)
      const pos = uv.mul(2).sub(1)
      const distToCenter = pos.sub(center.xy).length()
      const vertexDist = pos.sub(tri.a.xy).length()
                    .min(pos.sub(tri.b.xy).length())
                    .min(pos.sub(tri.c.xy).length())
      const centerGlow = smoothstep(0.05, 0.02, distToCenter)
      const vertexGlow = smoothstep(0.06, 0.03, vertexDist)
      const isInside = triangleContain(tri, vec3(pos, 0))
      const baseColor = vec3(0.2, 0.3, 0.5).mul(float(0.3).select(1, isInside))
      return vec4(baseColor.add(vec3(1, 0.8, 0.2).mul(centerGlow).mul(4)).add(vec3(0.9, 0.5, 0.7).mul(vertexGlow).mul(2)), 1)
})