const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
添加model
handler.setInputAction((movement) => {//鼠標左鍵事件,點擊地圖,在點擊位置添加模型
var cartesian = viewer.scene.globe.pick(viewer.camera.getPickRay(movement.position), viewer.scene);//獲取地形上的點
const newHeading = Cesium.Math.toRadians(0); //初始heading值賦0
const newPitch = Cesium.Math.toRadians(0);
const newRoll = Cesium.Math.toRadians(0);
const headingPitchRoll = new Cesium.HeadingPitchRoll(newHeading, newPitch, newRoll);
const modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(cartesian, headingPitchRoll, Cesium.Ellipsoid.WGS84, Cesium.Transforms.eastNorthUpToFixedFrame, new Cesium.Matrix4());
viewer.scene.primitives.add(Cesium.Model.fromGltf({
url, // 模型地址
modelMatrix,
}));
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
平移模型
handler.setInputAction((movement) => {
pick = viewer.scene.pick(movement.position);
if (pick != undefined) {
pick.primitive.silhouetteColor = Cesium.Color.RED; //選中模型後高亮
pick.primitive.silhouetteSize = 3.0;
handler.setInputAction((movement) => { //點擊模型後添加鼠標移動事件
const m1 = Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Matrix4.getTranslation(pick.primitive.modelMatrix, new Cesium.Cartesian3()), Cesium.Ellipsoid.WGS84, new Cesium.Matrix4());
const m3 = Cesium.Matrix4.multiply(Cesium.Matrix4.inverse(m1, new Cesium.Matrix4()), pick.primitive.modelMatrix, new Cesium.Matrix4());
const mat3 = Cesium.Matrix4.getRotation(m3, new Cesium.Matrix3());
const q = Cesium.Quaternion.fromRotationMatrix(mat3);
const hpr = Cesium.HeadingPitchRoll.fromQuaternion(q);
const headingPitchRoll = new Cesium.HeadingPitchRoll(hpr.heading, hpr.pitch, hpr.roll);// 獲取當前模型heading,pitch,roll
var cartesian = viewer.scene.globe.pick(viewer.camera.getPickRay(movement.endPosition), viewer.scene);// 獲取鼠標移動後的點
const m = Cesium.Transforms.headingPitchRollToFixedFrame(cartesian, headingPitchRoll, Cesium.Ellipsoid.WGS84, Cesium.Transforms.eastNorthUpToFixedFrame, new Cesium.Matrix4());
pick.primitive.modelMatrix = m;
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
模型旋轉
以調整Heading爲例
const curModelMatrix = curModel.modelMatrix; // 獲取當前模型modelMatrix
const cartesian = new Cesium.Cartesian3(curModelMatrix[12], curModelMatrix[13], curModelMatrix[14]);
const newHeading = Cesium.Math.toRadians(value);//改變Heading值
const newPitch = Cesium.Math.toRadians(pitch);// pitch值填當前模型pitch,上文介紹過如何獲取
const newRoll = Cesium.Math.toRadians(roll);// 同上
const headingPitchRoll = new Cesium.HeadingPitchRoll(newHeading, newPitch, newRoll);
const m = Cesium.Transforms.headingPitchRollToFixedFrame(cartesian, headingPitchRoll, Cesium.Ellipsoid.WGS84, Cesium.Transforms.eastNorthUpToFixedFrame, new Cesium.Matrix4());
curModel.modelMatrix = m; //新的modelMatrix賦給模型
模型比例
curModel.scale = 10;
模型透明度
curModel.color = Cesium.Color.WHITE.withAlpha(0.1);