XR-Frame 实现 始终朝向屏幕(相机)的面片与模型
wxml,xr-frame中plane平面默认是趴在场景中的,需要先绕x轴渲染90度,
// 面片
<xr-node id="l" position="-3.0 0 0.0">
<xr-mesh rotation="90 0 0" geometry="plane" uniforms="u_baseColorFactor:0.2 0.2 0.4 1, u_metallicRoughnessValues: 0 0.6" states="cullOn: false"></xr-mesh>
</xr-node>
// 模型
<xr-node id="b" position="0 0 -3.0">
<xr-gltf rotation="0 -90 0" scale="0.01 0.01 0.01" model="door"></xr-gltf>
</xr-node>
在场景的ready事件中获取相机,模型,并注册tick请求动画帧事件
handleReady({detail}) {
const xrScene = this.scene = detail.value;
const xrSystem = wx.getXrFrameSystem();
this.mat = new (xrSystem.Matrix4)();
const { width, height } = this.scene
this.cameraTrs = this.scene.getElementById('camera').getComponent(xrSystem.Transform);
this.leftTRS = this.scene.getElementById('l').getComponent(xrSystem.Transform);
this.backTRS = this.scene.getElementById('b').getComponent(xrSystem.Transform);
this.FACING = xrSystem.Vector3.createFromNumber(0, 0, 0);
this.UP = xrSystem.Vector3.createFromNumber(0, 1, 0);
xrScene.event.add('tick', this.handleTick.bind(this));
},
请求动画帧中,计算旋转四元数,更新模型朝向
handleTick: function () {
const xrSystem = wx.getXrFrameSystem();
if (this.leftTRS) {
const quaternion = this.leftTRS.quaternion;
// 算出从物体到相机的向量
this.FACING.set(this.cameraTrs.position).sub(this.leftTRS.position, this.FACING);
xrSystem.Quaternion.lookRotation(this.FACING, this.UP, quaternion);
}
if (this.backTRS) {
const quaternion = this.backTRS.quaternion;
// 算出从物体到相机的向量
this.FACING.set(this.cameraTrs.position).sub(this.backTRS.position, this.FACING);
xrSystem.Quaternion.lookRotation(this.FACING, this.UP, quaternion);
}
}