Home » Java » java – How do I rotate my camera around an object?-Exceptionshub

java – How do I rotate my camera around an object?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’ve been trying to learn OpenGL, LWJGL from scratch.
I’ve currently got a demo running of a camera looking at a world made of grass, at it’s center point I changed the texture to cobblestone just so it stands out.
I’m trying to implement a function in my camera class that will allow me to just pass a angle and have it rotate around a point.

My renderer has a 3 matrix transformations, one to translate the object in world space, another is a perspective transformation, and the last is my view transformation which is the camera.

I’ve positioned my camera at x:3, y:3, z:3, pitch: 45deg, yaw:45deg to get an isometric view of the world.

But no matter what I try I can’t seem to figure out how to rotate my camera around a position in world space?

Camera class

import org.joml.Vector3f;

public class Camera {
    private Vector3f position;
    private float pitch;
    private float yaw;
    private float roll;

    public Camera(Vector3f position, float pitch, float yaw, float roll) {
        this.position = position;
        this.pitch = pitch;
        this.yaw = yaw;
        this.roll = roll;
    }


    public Vector3f getPosition() {
        return position;
    }

    public float getPitch() {
        return pitch;
    }

    public float getYaw() {
        return yaw;
    }

    public float getRoll() {
        return roll;
    }
}

Function I use to create the view matrix

public static Matrix4f createViewMatrix(Camera camera){
        Matrix4f viewMatrix = new Matrix4f();
        viewMatrix.rotate((float) Math.toRadians(camera.getPitch()), new Vector3f(1,0,0));
        viewMatrix.rotate((float) Math.toRadians(camera.getYaw()), new Vector3f(0,1,0));
        Vector3f cameraPos = camera.getPosition();
        Vector3f negativeCameraPos = new Vector3f(-cameraPos.x, -cameraPos.y, -cameraPos.z);
        viewMatrix.translate(negativeCameraPos);
        return viewMatrix;
}

vertex shader code

#version 400 core

in vec3 position;
in vec2 textureCoords;

out vec2 pass_textureCoords;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void){
    gl_Position = projectionMatrix * viewMatrix * transformationMatrix * vec4(position, 1.0);
    pass_textureCoords = textureCoords;
}

This is how my camera is constructed

camera = new Camera(new Vector3f(-3, 3, 3), 45, 45, 0);

This is what it currently looks like when rendered:

img

How to&Answers: