Hide objects based on distance from camera

Hi all! I’m working on a small AR visualization of real estate. Our house models have several floors, and we would like to be able to iteratively hide floors (starting from the roof, then top floor, etc) based on where the camera is positioned. So if a user “zooms in” by moving his phone closer to the AR marker, the application should display lower floors.

Any pointers on how to achieve this? We already have all the AR stuff implemented and can view the model, so it’s only the occlusion part that I need help with. Ideally I’d like to have a fade-in/out effect on the floors, but at the moment I’m still stuck on calculating the camera distance to the model.

1 Like

You can do that with some vector maths on a getDistance.js script, on each model. Sample code:

// get reference points
var cameraPos = this.myCamera.getPosition();
var modelPos = this.entity.getPosition();

// get distance of model from camera
var distance = modelPos.sub(cameraPos).length();

if( distance < this.distanceThreshold){

   // show model
   this.entity.model.enabled = true;
}else{

   // hide model
   this.entity.model.enabled = false;
}
1 Like

That worked perfectly, thanks Leonidas!

Is there a fading effect built into PlayCanvas that I could leverage when enabling / disabling objects? I can probably also gradually change material alpha with a script, but that’s more complicated.

Glad it worked out.

No, there isn’t any build in effect but you can replicate it easily playing with the opacity of the material.

Check this: Is it possible to fadeIn or fadeOut the opacity with a group of entity?

1 Like

Thanks!

In case anyone else needs this, here’s a really great sample project for a fadeIN/OUT script:
https://developer.playcanvas.com/en/tutorials/fading-objects-in-and-out/

2 Likes