利用Cesium的 SampledPositionProperty来动态控制模型的位置,达到模型沿轨迹平滑移动的目的
本文中引用了第三方一个js库 turf.js
function initTrain() {
let newPositions = [
{"x": 6358638.974849774, "y": -498978.751542005, "z": 0},
{"x": 6358638.973079549, "y": -498978.75154201075, "z": 149.5383532969183}
];
let ALLLength = getPositionsLength(newPositions);
let eachStep = 0.05;
//Set the random number seed for consistent results.
Cesium.Math.setRandomNumberSeed(3);
//Set bounds of our simulation time
let start = Cesium.JulianDate.now();
let stop = Cesium.JulianDate.addSeconds(start, ALLLength * eachStep, new Cesium.JulianDate());
//Make sure viewer is at the desired time.
viewer.clock.startTime = start.clone();
viewer.clock.stopTime = stop.clone();
viewer.clock.currentTime = start.clone();
viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
viewer.clock.multiplier = 1;
viewer.clock.shouldAnimate = false;
let position = new Cesium.SampledPositionProperty();
for (let i = 0; i < newPositions.length; i++) {
let first = Array.from(newPositions);
let moveArray = first.slice(0, i + 1);
let moveLength = getPositionsLength(moveArray);
let time = Cesium.JulianDate.addSeconds(start, moveLength * eachStep, new Cesium.JulianDate());//时间递增
position.addSample(time, newPositions[i]);
}
let entity = viewer.entities.add({
availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
start: start,
stop: stop
})]),
model: {
uri: railwayModel,
minimumPixelSize: 0.001,
maximumScale: 0.001,
},
position: position,
orientation: new Cesium.VelocityOrientationProperty(position),
//viewFrom: new Cesium.Cartesian3(0.0, 0.0, 20.0)
});
viewer.trackedEntity = entity;
}
function getPositionsLength(centerline_cartesian) {
if (centerline_cartesian && centerline_cartesian.length > 1) {
let newPosition = centerline_cartesian.map((p) => cartesian2lonlat(p));
let line = turf.lineString(newPosition);
let options = {units: 'kilometers'};
let kiloLength = turf.length(line, options);
return parseFloat(kiloLength * 1000);
} else {
return 0;
}
}
效果展示: