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

center

简介

center 是 Yuka.js 库中的一个方法,用于将对象的中心点重新定位到指定位置。

语法

center( position = new Vector3() ) : this

参数

  • position:一个 Vector3 类型的参数,代表对象将要被重新定位到的位置,默认值为 new Vector3()

返回值

center 方法返回当前对象的 this

示例

import { Vector3 } from 'yuka';

class Entity {
    constructor( position = new Vector3() ) {
        this.position = position;
        this.box = {
            width: 10,
            height: 5,
            length: 20
        };
    }

    // 将 Entity 对象的中心点重新定位到 (10, 0, 5)。
    setPosition( x, y, z ) {
        this.position.set( x, y, z );
        const offset = new Vector3( this.box.width / 2, this.box.height / 2, this.box.length / 2 );
        this.position.sub( offset ); // 将当前位置向左上角偏移代表该对象的中心点
        return this.center();
    }

    // 将 Entity 对象的中心点回到原始位置。
    resetPosition() {
        this.position.add( new Vector3( this.box.width / 2, this.box.height / 2, this.box.length / 2 ) ); // 将当前位置向右下角偏移回原始位置
        return this;
    }

    // 将 Entity 对象重新定位到指定的目标位置,并将中心点位置相应调整。
    target( targetPosition ) {
        this.position.set( targetPosition.x, targetPosition.y, targetPosition.z );
        return this.center();
    }

    // 将 Entity 对象的中心点重新定位到指定位置。
    center( position = new Vector3() ) {
        const offset = new Vector3( this.box.width / 2, this.box.height / 2, this.box.length / 2 );
        this.position.add( offset ); // 将当前位置向右下角偏移代表该对象的中心点
        if ( position !== undefined ) {
            this.position.copy( position );
        }
        this.position.sub( offset ); // 将当前位置向左上角偏移代表该对象的中心点
        return this;
    }
}

上面的示例中定义了一个 Entity 类,它有一个默认的 position 属性,并在 setPositionresetPositiontarget 方法中都使用了 center 方法来重新定位该对象的中心点。

兼容性

  • 该方法要求浏览器支持 ES6 语法。
  • 支持 IE9 及以上版本。