oframe / ogl

Minimal WebGL Library
https://oframe.github.io/ogl/examples
3.61k stars 206 forks source link

Help with maintaining perspective ratio #199

Closed monolithMktg closed 3 months ago

monolithMktg commented 5 months ago

Guys I need someone to please guide me about maintaining the perspective/fov while changing viewport size. What I mean is, say I am working on desktop and I place a small cube and shift it right via JS so that it is about 2 finger away from the right edge of the canvas. Now I want it to maintain that space from the right edge proportionately to the changing size of the window/canvas all the way down to the mobile screens.

I am not sure what to target to achieve it: merely calculate new aspect ratio and feed it to the Camera class's aspect value? Or I update a matrix along with it?

Does any of the OGL example provide the solution?

Any help would be greatly appreciated.

monolithMktg commented 5 months ago

EDIT: Ok it looks like I have to update the projection matrix to make it work. Any in-built function which could help?

Why is even this resize code not working?

function resize() {
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.perspective({ 
        fov: 75, 
        aspect: gl.canvas.width / gl.canvas.height,
        near: 0.01,
        far: 20
    });
}
window.addEventListener('resize', resize, false);
resize();
monolithMktg commented 3 months ago

I reopened this thread because I seem to have fixed the "adjusting FOV to changing aspect ratio" issue I was originally having. The geometries now seem to 'proportionately' resize and stick to the same position on the x-axis when you resize to smaller widths. Should help in better mobile responsive behaviour.

I am not exactly sure what to call this, maybe "Horizontal FOV"? And if @gordonnl and @pschroen can take a look and maybe optimize further and incorporate it in an update where it can be toggled via the Camera class options then it'll be super cool.

The code in question: let fov = 2 * Math.atan( Math.tan( 75 * Math.PI / 180 / 2 ) / asp ) * 180 / Math.PI;

JSFiddle link for testing Try adding/removing fov from this.camera.perspective({aspect: asp, fov}); inside the resize() function to test the difference.