本文记录获取当前相机中心与地面的射线焦点的方法,可用于视角缩放过程中,控制视角自动平滑切换到二维等场景:
方法一定是视角中心能与地面有交集,如果对着地平线或对着天空肯定是没效果的。直接放代码:
//调整相机到正北方向 上帝视角
const limitViewerController=(viewer)=>{
try{
viewer.scene.screenSpaceCameraController.enableTilt = false; //禁止中键旋转视角
// 将相机朝向正北方向(即Z轴指向正北,Y轴指向正东)
var heading = Cesium.Math.toRadians(0.0); // 正北方向为90度
var pitch = Cesium.Math.toRadians(0.0); // 保持平面视角
var roll = 0.0; // 无滚动
var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
let camera_position = viewer.camera.position.clone();
let cameraHeight = viewer.camera.positionCartographic.height;
let camera = viewer.scene.camera;
const rayget = new Cesium.Ray(camera.position, camera.direction)
//射线监测 不到目标时 无法设置视角
const rayintersection = Cesium.IntersectionTests.rayEllipsoid(rayget, Cesium.Ellipsoid.WGS84);
if(rayintersection){
const raypoint = Cesium.Ray.getPoint(rayget, rayintersection.start);
// 获取当前使用的地球椭球体
var ellipsoid = viewer.scene.globe.ellipsoid;
// 将Cartesian3转换为经纬度
var raycartographic = ellipsoid.cartesianToCartographic(raypoint);
var cameracartographic = ellipsoid.cartesianToCartographic(camera_position);
// 获取经度、纬度和高度
var raylongitude = Cesium.Math.toDegrees(raycartographic.longitude);
var raylatitude = Cesium.Math.toDegrees(raycartographic.latitude);
var rayheight = cameracartographic.height;
const destinationPostion = Cesium.Cartesian3.fromDegrees(raylongitude, raylatitude, rayheight+100000);
viewer.camera.flyTo({
destination : destinationPostion,
duration: 1.5,
orientation : {
heading : 6.283185307179586,
pitch : -1.5707963267948966,
roll : 0.0
}
});
}
//调整也可以通过TWEEN.js 实现过渡动画
//import * as TWEEN from '@tweenjs/tween.js'
// const coords = {x: viewer.camera.heading, y: viewer.camera.pitch,z:viewer.camera.roll} // Start at (0, 0)
// const tween = new TWEEN.Tween(coords, false) // Create a new tween that modifies 'coords'.
// .to({x: 6.283185307179586, y: -1.5707963267948966, z:0}, 1000)
// .easing(TWEEN.Easing.Quadratic.InOut)
// .onUpdate((object) => {
// viewer.camera.setView({
// //destination : new Cesium.Cartesian3(raypoint.x, raypoint.y, camera_position.z),
// orientation: {
// heading: object.x, // 方向的朝向,以弧度为单位
// pitch: object.y, // 视角的高度,以弧度为单位
// roll: object.z // 绕着圆周运动的角度,一般设置为0
// }
// });
// // viewer.scene.camera.setView({
// // destination : new Cesium.Cartesian3(camera_position.x, camera_position.y, camera_position.z),
// // orientation: {
// // headingPitchRoll: new Cesium.HeadingPitchRoll(object.x, object.y, object.z)
// // }
// // });
// })
// .start() // Start the tween immediately.
// function animate() {
// tween.update()
// requestAnimationFrame(animate)
// }
// requestAnimationFrame(animate)
}catch(err){
console.log(err);
}
}