AABB
AlignmentBehavior
ArriveBehavior
AStar
BFS
BoundingSphere
BVH
BVHNode
Cell
CellSpacePartitioning
CohesionBehavior
CompositeGoal
ConvexHull
Corridor
CostTable
DFS
Dijkstra
Edge
EntityManager
EvadeBehavior
EventDispatcher
Behavior
FollowPathBehavior
FuzzyAND
FuzzyCompositeTerm
FuzzyFAIRLY
FuzzyModule
FuzzyOR
FuzzyRule
FuzzySet
FuzzyTerm
FuzzyVariable
FuzzyVERY
GameEntity
Goal
GoalEvaluator
Graph
GraphUtils
HalfEdge
HeuristicPolicyDijkstra
HeuristicPolicyEuclid
HeuristicPolicyEuclidSquared
HeuristicPolicyManhattan
InterposeBehavior
LeftSCurveFuzzySet
LeftShoulderFuzzySet
LineSegment
Logger
MathUtils
Matrix3
Matrix4
MemoryRecord
MemorySystem
MeshGeometry
MessageDispatcher
MovingEntity
NavEdge
NavMesh
NavMeshLoader
NavNode
Node
NormalDistFuzzySet
OBB
ObstacleAvoidanceBehavior
OffsetPursuitBehavior
OnPathBehavior
Path
Plane
Polygon
Polyhedron
PriorityQueue
PursuitBehavior
Quaternion
Ray
RectangleTriggerRegion
Regular
RightSCurveFuzzySet
RightShoulderFuzzySet
SAT
SeekBehavior
SeparationBehavior
SingletonFuzzySet
Smoother
SphericalTriggerRegion
State
StateMachine
SteeringBehavior
SteeringManager
Task
TaskQueue
Telegram
Think
Time
TriangularFuzzySet
Trigger
TriggerRegion
Vector3
Vehicle
Version
WanderBehavior

centroid

简介

centroid 是 Yuka js 库中的一个多边形(Polygon)对象方法,用于计算多边形重心的坐标。

语法

centroid( polygon )    

参数

  • polygon:一个可以用于表示多边形的点数组,例如 [[0,0],[0,1],[1,1],[1,0]]

返回值

  • 返回值是一个包含重心坐标 x 和 y 值的对象,例如 {x: 0.5, y: 0.5}

示例

const polygon = [[0,0],[0,1],[1,1],[1,0]];
const centroidCoord = centroid( polygon );
console.log(centroidCoord); // {x: 0.5, y: 0.5}

实现原理

计算多边形重心的坐标,可以通过以下公式求得:

$$\large X_c = \frac{\sum_{i=0}^{n-1}(x_i + x_{i+1}) * (x_i*y_{i+1} - x_{i+1}*y_i)}{6A}$$

$$\large Y_c = \frac{\sum_{i=0}^{n-1}(y_i + y_{i+1}) * (x_i*y_{i+1} - x_{i+1}*y_i)}{6A}$$

其中,$n$ 是多边形的边数,$A$ 是多边形面积。而多边形计算面积的方法,可以通过将多边形划分成多个三角形,再将其面积相加来计算。