gpt4 book ai didi

c++ - 根据鼠标选择Opengl拖动对象

转载 作者:行者123 更新时间:2023-11-28 02:07:21 25 4
gpt4 key购买 nike

要在 OpenGL 中使用鼠标选择对象,我需要做什么?我发现了类似选择缓冲区的东西,但我也读了一些它被弃用的地方。所以我被困住了,不知道要寻找什么。我也在使用 C++ 做这件事。

最佳答案

对于 2D,这是我正在使用的代码——您需要稍微修改一下,但希望它能给您一些想法。此代码为您提供“0 高度”的世界坐标——如果某些东西的高度不为 0,则可能无法根据视角正确选择它。

// for the current mouse position on the screen, where does that correspond to in the world?
glm::vec2 World::world_position_for_mouse(const glm::vec2 mouse_position,
const glm::mat4 projection_matrix,
const glm::mat4 view_matrix)
{
int window_width;
int window_height;
this->graphics.get_window_dimensions(window_width, window_height);

const int mouse_x = mouse_position[0];
const int mouse_y = mouse_position[1];

// normalize mouse position from window pixel space to between -1, 1
GLfloat normalized_mouse_x = (2.0f * mouse_x) / window_width - 1.0f;
float normalized_mouse_y = 1.0f - (2.0f * mouse_y) / window_height;


glm::vec3 normalized_mouse_vector = glm::vec3(normalized_mouse_x, normalized_mouse_y, 1.0f);

glm::vec4 ray_clip = glm::vec4(normalized_mouse_vector.xy(), -1.0, 1.0);

glm::vec4 ray_eye = glm::inverse(projection_matrix) * ray_clip;
ray_eye = glm::vec4(ray_eye.xy(), -1.0, 0.0);

glm::vec3 ray_world = (glm::inverse(view_matrix) * ray_eye).xyz();

ray_world = glm::normalize(ray_world);

float l = -(camera.z / ray_world.z);


return {camera.x + l * ray_world.x, camera.y + l * ray_world.y};
}

无论缩放如何,要以相同的“屏幕单位”平移世界,我根据上面代码的结果使用此代码:

    float camera_motion = time.get_wall_clock_delta() * camera_motion_per_second;
auto x1 = this->world_position_for_mouse(glm::vec2(1,0), this->cached_projection_matrix, this->cached_view_matrix).x;
auto x2 = this->world_position_for_mouse(glm::vec2(0,0), this->cached_projection_matrix, this->cached_view_matrix).x;
auto camera_change = (x1 - x2) * camera_motion;

其中 camera_motion 只是您希望它移动的速度与前一帧的时间增量相结合的乘数。基本上,你缩小得越远,每秒滚动得越快。无论缩放如何,窗口右边缘的任何像素都将花费恒定的时间到达左边缘。

关于c++ - 根据鼠标选择Opengl拖动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36975430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com