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

dispatchEvent

dispatchEvent()是Yuka.js中EventDispatcher类的一个方法,用于向注册在该事件调度程序(EventDispatcher)中的所有侦听器发送事件。

语法

dispatchEvent( event: Event ): this

参数

  • event:要发送的Event对象。

返回值

  • 返回当前EventDispatcher实例。

描述

所有实现EventDispatcher接口的对象都有一个dispatchEvent()方法,该方法用于向事件的所有注册侦听器(listener)发送Event事件。

Yuka.js的dispatchEvent()方法会首先在当前对象上面寻找具有匹配eventType类型的侦听器,如果当前侦听器的dispatcher属性指向当前对象,则直接调用当前侦听器的处理器方法。

如果当前对象上未找到匹配事件类型的侦听器,则事件调度程序会将事件一层一层地向上传递,直到事件到达“舞台”(stage)或根对象才会终止传递。

示例

import { EventDispatcher, Event } from 'yuka';

class Player extends EventDispatcher {
	constructor() {
        super();
        
        this.health = 100;
    }
    
    attack() {
        this.health -= 10;
        this.dispatchEvent( new Event( 'healthChanged' ) );
    }
}

let player = new Player();

player.addEventListener( 'healthChanged', ( event ) => {
	console.log( `Player health changed to ${event.target.health}!` );
});

player.attack(); // 输出 "Player health changed to 90!"

上述示例中,Player类继承了EventDispatcher,并在其attack()方法中触发了一个新的healthChanged事件。接下来,我们使用addEventListener()方法在player实例上注册了一个事件侦听器,该侦听器在每次healthChanged事件发生时都会在控制台中输出当前Player对象的健康状态。最后,我们调用player.attack()方法,传递了一个十点伤害值给Player对象,并触发了healthChanged事件,输出结果为“Player health changed to 90!”。