[英]Drag object based on mouse selection Opengl
為了在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
只是您希望其移動的速度與上一幀的時間增量相乘的乘數。 基本上,縮小得越遠,每秒滾動的速度就越快。 無論縮放如何,窗口右邊緣上的任何像素將花費固定的時間到達左邊緣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.