Search code examples
javavectorcameralibgdx

How to move a camera left and right in LibGDX


I have a camera which I control using WASD, but I'm stuck on moving it left and right. I've been looking all over the internet and it says to find a vector perpendicular to another you change the x and y round and times one of them by -1. I've tried this in the code below:

void camstrafe (String dir) {
    Vector3 direction = camera.direction.nor();
    Vector3 old = direction;
    direction.set(-old.z, 0, old.x);
    camera.translate(direction.scl(0.18f));
}

I have moving forwards working fine, and actually turning the camera round, but for some reason this doesn't work, and to be honest I'm not sure what it really does because when I press a or d (they call this function) the camera just goes crazy and starts turning round really quickly and sometimes going forwards or like a million miles sideways. Anyway, does anyone know how I could do this properly? By the way I've also tried getting the forward direction of the camera and using the .rotate() function rotating it 90 degrees right/left then translating it that way but that does the same thing. I'm thinking maybe cameras don't work the same was as other things do when translating them sideways/backwards.


Solution

  • To archive camera movement between 2 vectors use the camera lerp:

    public class myclass {
           [...]
    
             private OrthographicCamera camera;
             public Vector3 posCameraDesired;
    
                [...]
    
            private void processCameraMovement(){
                /// make some camera movement
                      posCameraDesired.x+=100.0f * Gdx.graphics.getDeltaTime();
                      posCameraDesired.y+=100.0f * Gdx.graphics.getDeltaTime();
                }
    
            [...]
    
                //render method
                public void draw(){
    
                [...]
    
                processCameraMovement();
                camera.position.lerp(posCameraDesired,0.1f);//vector of the camera desired position and smoothness of the movement
    
                [...]
    
    
    
                }