Search code examples
javascriptcesiumjs

How to get correct distance between tracked entity and camera in Cesium Js?


I want to get distance between an entity and camera in meters. To achieve that I'm passing cartesian3 positions of camera and entity in Cesium.Cartesian3.distanceSquared. It seems distance is calculating properly when the entity is not being tracked. But Tracked entity distance seems higher even though the camera is nearly moving along with the tracked entity.enter image description here

I'm not getting how to get correct distance between any entity (tracked/without tracked) and camera.

Entity can be anywhere on earth or in air and distance should not be the travelling distance.

viewer.clock.onTick.addEventListener(function (clock) {
  let epos = entity.position.getValue(clock.currentTime);
  let campos = viewer.camera.position;
  let distancebetween = Cesium.Cartesian3.distanceSquared(epos, campos);
  if (viewer.trackedEntity){
    console.log("Tracked:" + distancebetween);
  }else{
    console.log("NotTracked:" + distancebetween);
  }
});

Here is the Sandcastle link of what I'm trying to do.


Solution

  • You might have better luck using the camera's "world position" rather than its position within its own current coordinate frame. For example:

    let campos = viewer.camera.positionWC;
    

    I don't recommend using fields starting with an underscore, such as _positionCartographic. Those are intended to be private variables, and can change between Cesium releases without any notice.