首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C++/OpenGL中获取当前鼠标位置?

在C++/OpenGL中获取当前鼠标位置,可以通过监听鼠标事件来实现。以下是一个简单的示例:

  1. 首先,在窗口创建时,需要设置鼠标模式为隐藏并捕获鼠标。
代码语言:cpp
复制
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  1. 然后,在主循环中监听鼠标移动事件,并获取当前鼠标位置。
代码语言:cpp
复制
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
  1. 最后,可以将获取到的鼠标位置作为输入,进行相应的处理。
代码语言:cpp
复制
std::cout << "Mouse position: (" << xpos << ", " << ypos << ")"<< std::endl;

完整的示例代码如下:

代码语言:cpp
复制
#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中获取当前鼠标位置了。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券