cesium entity 移动和旋转的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const EventEmitter = require("events");

export default class Air extends EventEmitter {
constructor(viewer, uri, id, position, orientation) {
super();

this.active = false;
this.air = viewer.entities.add({
id: id,
position: position,
orientation: orientation,
viewFrom: new Cesium.Cartesian3(0, -30, 30),
model: {
uri,
scale: 0.04,
},
});
viewer.scene.preRender.addEventListener(this.update.bind(this));
}

update() {
const now = new Date().getTime();
if (this.active) {
if (this.startTime && this.endTime && this.startTime < now && now < this.endTime) {
const lerp = (now - this.startTime) / (this.endTime - this.startTime);
const posotion = Cesium.Cartesian3.lerp(this.initial.position, this.target.position, lerp, new Cesium.Cartesian3());
const orientation = Cesium.Quaternion.slerp(this.initial.orientation, this.target.orientation, lerp, new Cesium.Quaternion());
this.air.position = posotion;
this.air.orientation = orientation;
} else {
if (this.active) {
this.active = false;
this.emit("end");
if (!this.initial.position.equals(this.target.position)) this.emit("moved");
if (!this.initial.orientation.equals(this.target.orientation)) this.emit("rotated");
}
}
}
}

moveTarget({ position, orientation, speed = 5 }) {
this.initial = {
position: this.air.position.getValue(),
orientation: this.air.orientation.getValue(),
};
this.target = {
position: position || this.initial.position,
orientation: orientation || this.initial.orientation,
};
const duration = Cesium.Cartesian3.distance(this.initial.position, this.target.position) / speed || 2; // 如果没有移动位置,只有旋转则时间为两秒
this.startTime = new Date().getTime();
this.endTime = new Date(this.startTime + duration * 1000).getTime();
this.active = true;
}
}

重点在于使用Cesium.Cartesian3.lerp和 时间计算位置