asny / three-d

2D/3D renderer - makes it simple to draw stuff across platforms (including web)
MIT License
1.29k stars 109 forks source link

Centering the camera on a model #424

Closed xfdv closed 9 months ago

xfdv commented 9 months ago

Hi, sorry to bug you, but I'm trying to figure out how to position the camera to always keep an arbitrary model in view. I figure it'd be based on the model's bounding box somehow, and I've tried some code that works on particular models but not on others (because they're different sizes), but nothing definitive. I've also tried a 2D camera which does precisely fit the model in view, but it's clipped into it and I'm not sure how (or if?) I can control the 2D camera's depth.

I've mostly been trying to port Three.js code to three-d, but I thought I'd ask if you had any advice on going about this. Thanks a ton 😅

guija commented 9 months ago

Hi, can you maybe put a few examples of what you have tried already and what exactly is not working. I would say that you can use https://docs.rs/three-d-asset/latest/three_d_asset/struct.Camera.html#method.set_view . You can define pass the position + the target.

guija commented 9 months ago

Btw. this is not an issue, but a discussion. Please create a post in the discussion section and close this issue as you are not reporting a bug.

xfdv commented 9 months ago

Sorry, will do.

asny commented 9 months ago

Ah no please don't be like that. Issue or discussion, it doesn't matter, it's one click to convert an issue to a discussion 🤷‍♂️

Sounds like you could use an OrbitControl and set the target point, min and max distance based on the bounding box of the model. If you don't want the camera to move, you could just avoid handling events for the OrbitControl.

Another option is to use the Camera struct. If you want a 2D camera (orthographic projection), you can 'zoom' by changing the height. If you use a 3D camera (perspective projection) you need to move the camera towards or away from the object to zoom.