Search code examples
androidlibgdxperspectivecamera

Moving PerspectiveCamera using Touchpad


I have a Touchpad which I want to use to move my camera. My current code moves the camera by adding the camera.direction vector scaled by 1 to the position vector. It seems that I can't use anything less than one because it starts rotating weirdly when I do. I am wanting to use the

touchpad.getKnobPercentX()
touchpad.getKnobPercentY()

methods to scale it based on the position of the knob. The problem with this is that it returns a value that is less than one. Anything greater than one moves the camera too fast. This is the code I am using to update my camera since I can't use the Touchpad knob.

private void setKnobAction() {
    if (pad.getKnobPercentY() > 0f) {
        camera.position.add(camera.direction.scl(1f));
        camera.update();
    }
    if (pad.getKnobPercentY() < 0f) {
        camera.position.sub(camera.direction.scl(1f));
        camera.update();
    }
    if (pad.getKnobPercentX() > 0f) {
        right = camera.direction.cpy().crs(Vector3.Y).nor();
        camera.position.add(right.scl(1));
        camera.update();
    }
    if (pad.getKnobPercentX() < 0f) {
        right = camera.direction.cpy().crs(Vector3.Y).nor();
        camera.position.sub(right.scl(1));
        camera.update();
    }
}

This method is getting called in my render() method so it is getting called several times. Also, if the knobPercent is at 0, it will start rotating weirdly.


Solution

  • The javadoc of Vector3.scl(float scalar) says:

    Scales this vector by a scalar

    This means, that you actually scale the camera.direction Vector.
    Given, that a direction Vector usually is a Vector3 with a length of 1, giving the percentage of each axis you should notice the problem.
    Scaling it up results in faster movement each frame, scaling it down results in slower movement each frame.
    For example: You move in x-Direction, your camera.direction is Vector3(1, 0, 0). You scale it by 2.
    Now it is Vector3(2, 0, 0) and you move by 2 units in this frame. Again, it is scaled and in the next frame it is Vector3(4, 0, 0), you move by 4 units in this frame. And so it goes on and on.
    The same goes for scaling lower then 1.

    Even worse is a scaling with zero, cause it sets the length of the camera.direction to zero. This means, that you don't have any informations about the direction anymore, which causes the strange rotation.

    So what you shoul do:
    Store another Vector3, copy the values of camera.direction to it (at the beginning of each frame), scale it by the getKnobPercentY() (actually you should scale it by getKnobPercentY() * delta * speed) and add this to the position.
    Then reset this Vector again (copy the values of the camera.direction to it) and do the same things for the x-values (ofc now with the crs(Vector3.Y))