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
属性,并在 setPosition
、resetPosition
、target
方法中都使用了 center
方法来重新定位该对象的中心点。
ES6
语法。