Hello I'm following opengl tutorial from this page and trying to implement a camera class. Here's my camera class code.
class Camera
{
public:
static float fov;
glm::vec3 pos;
glm::vec3 front;
glm::vec3 up;
bool firstMouse;
float screen_width;
float screen_height;
Camera(float screen_width, float screen_height);
~Camera();
void setup_scroll_inputs(GLFWwindow* window);
static void scroll_callback_static(GLFWwindow* window, double xoffset, double yoffset);
};
and cpp
void Camera::setup_scroll_inputs(GLFWwindow* window)
{
glfwSetScrollCallback(window, Camera::scroll_callback_static);
}
void Camera::scroll_callback_static(GLFWwindow* window, double xoffset, double yoffset)
{
fov -= (float)yoffset;
if (fov < 20.0f)
fov = 20.0f;
if (fov > 100.0f)
fov = 100.0f;
}
What I want to achieve is zoom-in and zoom-out feature whenever I scroll up or down.
I tried to put glfwSetScrollCallback
function in the camera class member function because
I want to keep my main function as clean as possible.
My scroll_callback
function has to be a static member function since glfwSetScrollCallback
is expecting a function pointer.
However, I want to make it possible for the scroll_callback
function to access camera's member variables.
Is there a way to achieve this?
At the moment, I made fov to be a static member variable since my scrollback function would not have access to it otherwise.
A static function won't be able to access members of the class. You can use a non-capturing lambda to connect it
To access your camera object you'll need to store a pointer to it using glfwSetWindowUserPointer
and retrieve it inside the lambda using glfwGetWindowUserPointer
glfwSetWindowUserPointer(window, &camera);
glfwSetScrollCallback(window, [](GLFWwindow* window,double xoffset, double yoffset) {
Camera* camera = (Camera*)glfwGetWindowUserPointer(window);
camera->scroll_callback(window, xoffset, yoffset);
});