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

distanceToPoint

Polygon类的distanceToPoint方法可以计算一个点到多边形的最短距离。该方法的实现基于欧几里得距离公式。

语法

polygon.distanceToPoint(point)

参数

  • point: Object 要计算距离的点,格式为 {x: number, y: number}

返回值

距离输入点最近的多边形边的距离。

示例

const polygon = new Yuka.Polygon([
    new Yuka.Vector3(-2, -2),
    new Yuka.Vector3(2, -2),
    new Yuka.Vector3(2, 2),
    new Yuka.Vector3(-2, 2)
]);

const point = { x: 1, y: 1 };
const distance = polygon.distanceToPoint(point);
console.log(distance); // 输出 0.41421356237309515

实现原理

该方法计算一个点到多边形的最短距离。首先,获取多边形所有边的起始点和终止点,然后对每条边计算点到直线的距离。如果输入点在边的两侧,则距离为点到直线的距离;否则,距离为输入点到边端点的最短距离。由此得出距离最小的边,并返回该距离。

注意事项

  • 该方法的输入点可以在多边形内部或外部。
  • 如果该多边形不是凸多边形,则该方法不能保证得出正确的结果。
  • 在使用本方法时,请确保多边形的点按照逆时针方向排列。

参考文献