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

Yuka.js - Dijkstra算法的source

介绍

Dijkstra算法是一个在图中寻找最短路径的算法,它以一个节点作为起点,计算到其他所有节点的最短路径。Yuka.js库提供了Dijkstra算法对于场景图中的寻路非常有用。

使用方法

在Yuka.js库中,Dijkstra算法提供了Dijkstra类。在使用之前,需要先实例化一个graph对象,传入节点数据和连接节点的边。

const graph = new Graph();

graph.addNode( node1 );
graph.addNode( node2 );
graph.addNode( node3 );

graph.connect( node1, node2, 1 );
graph.connect( node1, node3, 2 );
graph.connect( node2, node3, 1 );

可以在graph对象中,添加多个节点,并通过connect方法连接节点,设置边的距离。当要使用Dijkstra算法寻找最短路径时,需要使用以下代码:

const dijkstra = new Dijkstra( graph );
const path = dijkstra.search( node1, node3 );

在Dijkstra类的构造函数中,传入先前创建的graph对象。在调用search方法时,传入起点和终点。search方法返回一个从起点到终点最短路径上的所有节点。

示例

以下代码展示如何使用Dijkstra算法寻找两个节点之间的最短路径:

import { Graph, Dijkstra } from 'yuka';

// 创建节点和连接
const node1 = { position: new Vector3( 0, 0, 0 ) };
const node2 = { position: new Vector3( 0, 0, 1 ) };
const node3 = { position: new Vector3( 1, 0, 1 ) };
const graph = new Graph();

graph.addNode( node1 );
graph.addNode( node2 );
graph.addNode( node3 );

graph.connect( node1, node2, 1 );
graph.connect( node1, node3, 2 );
graph.connect( node2, node3, 1 );

// 使用Dijkstra算法寻找最短路径
const dijkstra = new Dijkstra( graph );
const path = dijkstra.search( node1, node3 );

// 输出路径节点
for ( let i = 0, l = path.length; i < l; i ++ ) {
	console.log( path[ i ].position );
}

上述代码将会打印出:

Vector3 { x: 0, y: 0, z: 0 }
Vector3 { x: 0, y: 0, z: 1 }
Vector3 { x: 1, y: 0, z: 1 }

这三个节点就是最短路径上的所有节点。