Search code examples
javaandroidlibgdx

How to bound the pinch zoom in libGDX?


I have been trying to sort out the pinch zooming for a CameraInputController. I want it to zoom in and out of the origin, but be bounded between 3 and 10. I put this bit of code in the zoom() function:

public boolean zoom (float amount) {
if(camera.position.len() < 3 && amount > 0)
{
    return  false;
}
if(camera.position.len() > 10 && amount < 0)
{
    return false;
}
if (!alwaysScroll && activateKey != 0 && !activatePressed)
    return false;
Gdx.app.log("zoom", amount + "");
camera.translate(tmpV1.set(camera.direction).scl(amount));
if (scrollTarget)
    target.add(tmpV1);
if (autoUpdate)
    camera.update();
return true;

}

This works fine if I just call the zoom function (for example a zoom button), but when I pinch zoom, the camera is able to zoom in way past 3, and when zooming out the camera jumps in quite drastically when it gets near to 10. Strangely, the pinch zooming is very smooth if I don't have these bounds.

If I output the amount variable, then pinch zooming gives me quite a range of numbers, something like this when zooming out:

-3.4762511    
3.425479
-3.386308
3.353984

and this when zooming in:

3.6231816
-3.553997
3.8673449
-3.81199

When I look at the zoom() function inside the CameraGestureListener, the amount value in that is also varying loads. If I look at the pinch() function, then each time it is called the pointer2 position alternates between the position of the first and second finger.

Could this be a bug? Anyone got any idea what is happening? And how I can sort this out?


Solution

  • I figured it out myself! Turns out If you just check for the camera position and move it to where you want in the render() function, rather than in the listeners inside the camera controller, then everything works fine. I guess I was over complicating it somewhat.