在C++/OpenGL中获取当前鼠标位置,可以通过监听鼠标事件来实现。以下是一个简单的示例:
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
std::cout << "Mouse position: (" << xpos << ", " << ypos << ")"<< std::endl;
完整的示例代码如下:
#include <GLFW/glfw3.h>
#include<iostream>
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
std::cout << "Mouse position: (" << xpos << ", " << ypos << ")"<< std::endl;
}
int main()
{
if (!glfwInit())
{
std::cout << "Failed to initialize GLFW"<< std::endl;
return -1;
}
GLFWwindow* window = glfwCreateWindow(800, 600, "My Window", NULL, NULL);
if (!window)
{
std::cout << "Failed to create GLFW window"<< std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
mouse_callback(window, xpos, ypos);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
这样,就可以在C++/OpenGL中获取当前鼠标位置了。
领取专属 10元无门槛券
手把手带您无忧上云