Steven Chen avatar image
1 Like"
Steven Chen asked Jason Lightfoot edited

Calculate distance from camera to object


I am working on something like the LOD feature, that only execute some drawing code at proximity.

How to calculate distance between camera and an object? Does camera have xyz position value?

If possible, I also want to calculate the percentage occupied on screen of an object. But I don't know how to achieve that.


FlexSim 23.2.1
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

1 Answer

Jason Lightfoot avatar image
Jason Lightfoot answered Jason Lightfoot edited

Here's the distance calculation for use in the ondrawtrigger - with code to hide the contents if over 20m away.

// If this function returns a true, the default draw code of the object will not be executed.
Vec3 mgroundviewpoint=Vec3(viewpointx(view).value,viewpointy(view).value,viewpointz(view).value);
Vec3 mcurrcentre=current.getLocation(0.5,0.5,0.5).project(current.up,model());
Vec3 groundpath=mgroundviewpoint-mcurrcentre;
double azimuth=-1*viewpointrx(view).value;
double elevation=Math.radians(azimuth);
double viewradius=viewpointradius(view).value;
double groundradius=Math.cos(elevation)*viewradius;
double z=Math.sin(elevation)*viewradius;
double bearing=viewpointrz(view).value-90;
double rotation=Math.radians(bearing);
double y=Math.sin(rotation)*groundradius;
double x=Math.cos(rotation)*groundradius;
Vec3 topov=Vec3(x,y,z);
Vec3 mpov=mgroundviewpoint+topov;
Vec3 path=mpov-mcurrcentre;
if (path.magnitude>20)

Note the existance of the checkbox for fustrum culling and the FlexSim function distfromviewpoint() which, as the print statement in the code above demonstrates, yields different values (which were often incorrect when I tested it).

5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.