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);