cesiumJS中,根据已知点位进行第一视角漫游并且镜头平滑转向的代码实现
效果
代码
function initMove(){
// 点位数据
const points = [
Cesium.Cartesian3.fromDegrees(112.76808874621787, 35.174973419915396, 2), // 点1
Cesium.Cartesian3.fromDegrees(112.76808013112193, 35.17600542306012, 2), // 点2
Cesium.Cartesian3.fromDegrees(112.7680757112957, 35.176803887395265, 2), // 点3
Cesium.Cartesian3.fromDegrees(112.76812098091747, 35.1769452803711, 2), // 点4
Cesium.Cartesian3.fromDegrees(112.76826823232298, 35.17694348179523, 2), // 点5
Cesium.Cartesian3.fromDegrees(112.77095423366187, 35.176981576086455, 2), // 点6
Cesium.Cartesian3.fromDegrees(112.77102800722801, 35.174977361231996, 2), // 点7
Cesium.Cartesian3.fromDegrees(112.76808874621787, 35.174973419915396, 2), // 点8
];
// 漫游时间
let totalTime = 60
let startTime = this.viewer.clock.currentTime.clone()
let stopTime = Cesium.JulianDate.addSeconds(
startTime,
totalTime,
new Cesium.JulianDate()
);
const property = new Cesium.SampledPositionProperty();
points.forEach((ele,index)=>{
const time = Cesium.JulianDate.addSeconds(
startTime,
index*(totalTime/(points.length)),
new Cesium.JulianDate()
);
property.addSample(time, ele);
this.viewer.entities.add({
position: ele,
point: {
pixelSize: 8,
color: Cesium.Color.TRANSPARENT,
outlineColor: Cesium.Color.YELLOW,
outlineWidth: 3,
},
});
})
let orientation = new Cesium.VelocityOrientationProperty(property);
const entity = this.viewer.entities.add({
availability: new Cesium.TimeIntervalCollection([
new Cesium.TimeInterval({
start: startTime,
stop: stopTime,
}),
]),
position: property,
orientation: orientation,
path: {
resolution: 1,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.1,
color: Cesium.Color.YELLOW,
}),
width: 10,
},
});
let lastOrientation = new Cesium.Quaternion();
this.viewer.clock.onTick.addEventListener((e)=>{
try {
if(this.viewer.clock.shouldAnimate === true){
let ori = orientation.getValue(this.viewer.clock.currentTime);//获取偏向角
let center = property.getValue(this.viewer.clock.currentTime);//获取位置
if(!ori || !center){
console.warn('Orientation or position为空');
return;
}
// 平滑转向
const smoothedOri = Cesium.Quaternion.slerp(
lastOrientation,
ori,
0.1, // 插值因子
new Cesium.Quaternion()
);
lastOrientation = Cesium.Quaternion.clone(smoothedOri);
let transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Matrix3.fromQuaternion(smoothedOri), center);//将偏向角转为3*3矩阵,利用实时点位转为4*4矩阵
this.viewer.camera.lookAtTransform(transform, new Cesium.Cartesian3(-10, 0, 0));//将相机向后面放一点
}
} catch (error) {
console.error('error',error)
}
});
}