作者:幼儿之家燕郊_880 | 来源:互联网 | 2024-11-24 14:39
本文继续探讨在上一章节中构建的地球模型基础上,如何通过自定义的`CameraEarthWheelControl`类来实现更精细的地图缩放控制。我们将深入解析该类的实现细节,并展示其在实际项目中的应用。
在前一篇文章中,我们介绍了如何创建一个基础的地球模型并设置相机。现在,我们将进一步探索如何通过自定义控件增强用户体验,特别是通过鼠标滚轮实现平滑的缩放效果。
为了实现这一功能,我们引入了 `CameraEarthWheelControl` 类,该类专门用于处理鼠标滚轮事件,以调整相机的视角和缩放级别。
const BABYLON = require('babylonjs');
import { EarthTool } from './EarthTool';
export class CameraEarthWheelControl {
constructor(camera) {
this.camera = camera;
this.wheelPrecision = 3;
this.wheelDeltaPercentage = 0;
this._maxRadius = 150;
this._minRadius = 50;
}
getTypeName() {
return null;
}
getClassName() {
return "CameraEarthWheelControl";
}
getSimpleName() {
return "earthmousewheel";
}
computeDeltaFromMouseWheelLegacyEvent(e, t) {
let delta = 0;
const adjustment = 0.01 * e * this.wheelDeltaPercentage * t;
delta = e > 0 ? adjustment / (1 + this.wheelDeltaPercentage) : adjustment * (1 + this.wheelDeltaPercentage);
return delta;
}
attachControl(canvas, add) {
const origin = BABYLON.Vector2.Zero();
this._wheelHandler = (event, pickResult) => {
if (event.type !== BABYLON.PointerEventTypes.POINTERWHEEL) return;
const nativeEvent = event.event;
let delta = 0, wheelDelta = 0;
if (nativeEvent.wheelDelta) {
wheelDelta = nativeEvent.wheelDelta;
} else {
wheelDelta = 60 * -(nativeEvent.deltaY || nativeEvent.detail);
}
if (this.wheelDeltaPercentage) {
delta = this.computeDeltaFromMouseWheelLegacyEvent(wheelDelta, this.camera.radius);
if (delta > 0) {
let radius = this.camera.radius,
inertialOffset = this.camera.inertialRadiusOffset + delta;
for (let i = 0; i <20 && Math.abs(inertialOffset) > 0.001; i++) {
radius -= inertialOffset;
inertialOffset *= this.camera.inertia;
}
radius = BABYLON.Scalar.Clamp(radius, 0, Number.MAX_VALUE);
delta = this.computeDeltaFromMouseWheelLegacyEvent(wheelDelta, radius);
}
} else {
delta = wheelDelta > 0 ? EarthTool.MapNumberToInterval(this.camera.radius, 220, 50, 10, 1e-4) : -EarthTool.MapNumberToInterval(this.camera.radius, 220, 50, 10, 1e-4);
let inertia = EarthTool.MapNumberToInterval(this.camera.radius, 220, 50, 0.9, 0.2);
if (inertia > 0.9) inertia = 0.9;
if (inertia <0) inertia = 0;
this.camera.inertia = inertia;
}
if (delta) {
this.camera.inertialRadiusOffset += delta;
}
if (nativeEvent.preventDefault) {
nativeEvent.preventDefault();
}
};
this._observer = this.camera.getScene().onPointerObservable.add(this._wheelHandler, BABYLON.PointerEventTypes.POINTERWHEEL);
this._pointerHandler = () => {
const deltaX = (this.camera.latLonAtMouse.x - origin.x) * Math.PI / 180,
deltaY = (this.camera.latLonAtMouse.y - origin.y) * Math.PI / 180;
if (this.camera.distance) {
this.camera.inertialAlphaOffset += deltaY / 5;
}
};
}
}
以上代码实现了对鼠标滚轮事件的监听和处理,通过计算滚动增量来动态调整相机的缩放比例,从而达到更加自然和平滑的用户交互体验。更多详细信息和示例代码可以在 这里 查看。