0
\$\begingroup\$

I am working on a 2D isometric perspective game using SDL2 and I would like to implement the ability to pan the map when the right mouse button is held down.

I was wondering what is best way to set this up? My existing solutions involve checking if the mouse button is held down and if it is, moving the camera relative to the direction of the motion of the mouse. But this is not very responsive and leads to stuttering.

I wonder if there is a generally agreed upon way of doing this?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It's difficult to understand what you mean by stuttering (is the camera panning too fast? Or is there tearing?), but here's a way to implement smooth camera movement.

For the sake of simplicity, I assume your camera has two variables cameraX and cameraY which determine the camera's position.

Add 2 new variables, cameraTargetX and cameraTargetY.

The idea is, every time the mouse moves the camera, instead of modifying the variables cameraX and cameraY it will move the cameraTargetX and cameraTargetY. Then in your Update you modify the value of cameraX and cameraY to get closer to cameraTargetX and cameraTargetY like so:

void update() {
    cameraX += cameraTargetX -cameraX *0.5;
    cameraY += cameraTargetY -cameraY *0.5;
}

This will cause the camera to move half the distance towards the target every frame. This is only an example, you can make a custom formula depending on how your game currently works, but hopefully this is enough to show a method of achieving this.

I wonder if there is a generally agreed upon way of doing this?

In general with game development, there's multiple ways of doing things. As long as you get the desired result that runs with acceptable resources, you are good to go.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Since the result is a exponential decay, I suggest using a much lower value than 0.5 for most use cases. This exact value would depend approximately on the square root of the number of frame-rate and distance dependent steps to get close to the target. I usually start with .125, 1/8th, and adjust from there. \$\endgroup\$
    – agone
    Dec 8, 2023 at 22:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .