簡體   English   中英

對於鼠標單擊光線投射一條線,為什么在我移動相機后我的起始光線沒有更新到我的相機 position?

[英]For mouse click ray casting a line, why aren't my starting rays updating to my camera position after I move my camera?

當相機移動時,為什么我的起始光線仍然停留在原點 0、0、0,即使相機 position 已經更新?

如果我啟動程序並且我的相機 position 的默認值為 0、0、0,它工作正常。但是一旦我將相機移動到右側並單擊更多,線條仍然來自 0 0 0從相機所在的任何地方開始。 我做錯了什么嗎? 我已經檢查以確保它們在主循環中得到更新。 我使用了以下引用的代碼片段:
在 3D 中使用 NinevehGL 或 OpenGL i-phone 進行光線追蹤

// 1. Get mouse coordinates then normalize
float x = (2.0f * lastX) / width - 1.0f;
float y = 1.0f - (2.0f * lastY) / height;

// 2. Move from clip space to world space
glm::mat4 inverseWorldMatrix = glm::inverse(proj * view);
glm::vec4 near_vec = glm::vec4(x, y, -1.0f, 1.0f);
glm::vec4 far_vec = glm::vec4(x, y, 1.0f, 1.0f);
glm::vec4 startRay = inverseWorldMatrix * near_vec;
glm::vec4 endRay = inverseWorldMatrix * far_vec;

// perspective divide
startR /= startR.w;
endR /= endR.w;

glm::vec3 direction = glm::vec3(endR - startR);

// start the ray points from the camera position
glm::vec3 startPos = glm::vec3(camera.GetPosition());
glm::vec3 endPos = glm::vec3(startPos + direction * someLength);

第一個截圖我點擊了一些光線,第二個我將我的相機向右移動並點擊了一些,但初始的起始光線仍然在 0,0,0。我正在尋找的是光線從任何地方出來相機 position 在第三張圖像中,即紅色光線抱歉造成混亂,紅色線條應該射出並射入遠處而不是向上。

3d 射線投射鼠標點擊

// and these are my matrices
// projection
glm::mat4 proj = glm::perspective(glm::radians(camera.GetFov()), (float)width / height, 0.1f, 100.0f);
// view
glm::mat4 view = camera.GetViewMatrix(); // This returns glm::lookAt(this->Position, this->Position + this->Front, this->Up);
// model
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f));

很難說問題出在代碼的哪里。 但是,我使用這個 function 進行光線投射,它改編自從頭開始像素和 learnopengl 的代碼:

vec3 rayCast(double xpos, double ypos, mat4 projection, mat4 view) {
    // converts a position from the 2d xpos, ypos to a normalized 3d direction
    float x = (2.0f * xpos) / WIDTH - 1.0f;
    float y = 1.0f - (2.0f * ypos) / HEIGHT;
    float z = 1.0f;
    vec3 ray_nds = vec3(x, y, z);
    vec4 ray_clip = vec4(ray_nds.x, ray_nds.y, -1.0f, 1.0f);
    // eye space to clip we would multiply by projection so
    // clip space to eye space is the inverse projection
    vec4 ray_eye = inverse(projection) * ray_clip;
    // convert point to forwards
    ray_eye = vec4(ray_eye.x, ray_eye.y, -1.0f, 0.0f);
    // world space to eye space is usually multiply by view so
    // eye space to world space is inverse view
    vec4 inv_ray_wor = (inverse(view) * ray_eye);
    vec3 ray_wor = vec3(inv_ray_wor.x, inv_ray_wor.y, inv_ray_wor.z);
    ray_wor = normalize(ray_wor);
    return ray_wor;
}

您可以使用startPos = camera.PositionendPos = camera.Position + rayCast(...) * scalar_amount來畫線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM