MCPcopy Create free account
hub / github.com/ByteArena/box2d / ComputeCentroid

Function ComputeCentroid

CollisionB2ShapePolygon.go:100–140  ·  view source on GitHub ↗
(vs []B2Vec2, count int)

Source from the content-addressed store, hash-verified

98}
99
100func ComputeCentroid(vs []B2Vec2, count int) B2Vec2 {
101
102 B2Assert(count >= 3)
103
104 c := MakeB2Vec2(0, 0)
105 area := 0.0
106
107 // pRef is the reference point for forming triangles.
108 // It's location doesn't change the result (except for rounding error).
109 pRef := MakeB2Vec2(0.0, 0.0)
110
111 inv3 := 1.0 / 3.0
112
113 for i := 0; i < count; i++ {
114 // Triangle vertices.
115 p1 := pRef
116 p2 := vs[i]
117 p3 := MakeB2Vec2(0, 0)
118 if i+1 < count {
119 p3 = vs[i+1]
120 } else {
121 p3 = vs[0]
122 }
123
124 e1 := B2Vec2Sub(p2, p1)
125 e2 := B2Vec2Sub(p3, p1)
126
127 D := B2Vec2Cross(e1, e2)
128
129 triangleArea := 0.5 * D
130 area += triangleArea
131
132 // Area weighted centroid
133 c.OperatorPlusInplace(B2Vec2MulScalar(triangleArea*inv3, B2Vec2Add(B2Vec2Add(p1, p2), p3)))
134 }
135
136 // Centroid
137 B2Assert(area > B2_epsilon)
138 c.OperatorScalarMulInplace(1.0 / area)
139 return c
140}
141
142func (poly *B2PolygonShape) Set(vertices []B2Vec2, count int) {
143 B2Assert(3 <= count && count <= B2_maxPolygonVertices)

Callers 1

SetMethod · 0.85

Calls 8

B2AssertFunction · 0.85
MakeB2Vec2Function · 0.85
B2Vec2SubFunction · 0.85
B2Vec2CrossFunction · 0.85
B2Vec2MulScalarFunction · 0.85
B2Vec2AddFunction · 0.85
OperatorPlusInplaceMethod · 0.45

Tested by

no test coverage detected