[CesiumJS]Cesium Getting Started 12 - Camera Modes

To showcase our drone flight, let’s experiment with camera modes. We’ll keep it simple with two basic camera modes that the user can switch between:

  • Free Mode : Default camera controls.
  • Drone Mode : Makes the camera follow the drone through the flight at a fixed distance.

Free mode doesn’t require any code since it uses the default controls. As for drone follow mode, we can use the camera’s built-in entity tracking feature to position the camera and orient it toward the drone with an offset. This keeps the camera at a fixed offset from the specified entity even while it’s moving. To track an entity, we simply set viewer.trackedEntity.

To switch to free camera mode, we can set viewer.trackedEntity to undefined, then use camera.flyTo() to return to our home view.

Here are the camera mode functions:

1
2
3
4
5
6
7
8
9
// Create a follow camera by tracking the drone entity
function setViewMode() {
    if (droneModeElement.checked) {
        viewer.trackedEntity = drone;
    } else {
        viewer.trackedEntity = undefined;
        viewer.scene.camera.flyTo(homeCameraView);
    }
}

To attach this to HTML input, we can attach this function to the change event on the appropriate elements:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var freeModeElement = document.getElementById('freeMode');
var droneModeElement = document.getElementById('droneMode');

// Create a follow camera by tracking the drone entity
function setViewMode() {
    if (droneModeElement.checked) {
        viewer.trackedEntity = drone;
    } else {
        viewer.trackedEntity = undefined;
        viewer.scene.camera.flyTo(homeCameraView);
    }
}

freeModeElement.addEventListener('change', setCameraMode);
droneModeElement.addEventListener('change', setCameraMode);

Finally, entities are automatically tracked when the user double-clicks on them. If the user starts tracking the drone by clicking, we can add some handling to automatically update the UI:

1
2
3
4
5
6
viewer.trackedEntityChanged.addEventListener(function() {
    if (viewer.trackedEntity === drone) {
        freeModeElement.checked = false;
        droneModeElement.checked = true;
    }
});

Here are our two camera modes – we can now freely switch to the drone camera view, which looks like this:

Cesium Chinese Community QQ Group: 807482793

Original link: http://cesiumcn.org/topic/165.html | China fast access: http://cesium.coinidea.com/topic/165.html