簡體   English   中英

OpenGL - 第一人稱相機矩陣問題

[英]OpenGL - Trouble with first person camera matrix

我盡力創造一個模仿第一人稱相機風格的相機。 我剛剛從舊的OpenGL渲染方法切換到現在准備處理相機矩陣。 這是我的相機更新代碼。

void Camera::update(float dt)
{
// Get the distance the camera has moved
float distance = dt * walkSpeed;

// Get the current mouse position
mousePos = mouse->getPosition();

// Translate the change to yaw and pitch
angleYaw -= ((float)mousePos.x-400.0f)*lookSpeed/40;
anglePitch -= ((float)mousePos.y-300.0f)*lookSpeed/40;

// Clamp the camera to a max/min viewing pitch
if(anglePitch > 90.0f)
    anglePitch = 90.0f;

if(anglePitch < -90.0f)
    anglePitch = -90.0f;

// Reset the mouse position
mouse->setPosition(mouseReset);

// Check for movement events
sf::Event event;
while (window->pollEvent(event))
{

    // Calculate the x, y and z values of any movement
    if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::W)
    {
        position.x -= (float)sin(angleYaw*M_PI/180)*distance*25;
        position.z += (float)cos(angleYaw*M_PI/180)*distance*25;
        position.y += (float)sin(anglePitch * M_PI / 180) * distance * 25;
        angleYaw = 10.0;
    }
    if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::S)
    {
        position.x += (float)sin(angleYaw*M_PI/180)*distance*25;
        position.z -= (float)cos(angleYaw*M_PI/180)*distance*25;
        position.y -= (float)sin(anglePitch * M_PI / 180) * distance * 25;
    }
    if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::R)
    {
        position.x += (float)cos(angleYaw*M_PI/180)*distance*25;
        position.z += (float)sin(angleYaw*M_PI/180)*distance*25;
    }
    if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::A)
    {
        position.x -= (float)cos(angleYaw*M_PI/180)*distance*25;
        position.z -= (float)sin(angleYaw*M_PI/180)*distance*25;
    }
}

// Update our camera matrix
camMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(-position.x, -position.z, -position.y));
camMatrix = glm::rotate(camMatrix, angleYaw, glm::vec3(0, 1, 0));
camMatrix = glm::rotate(camMatrix, anglePitch, glm::vec3(1, 0, 0));
}

最后3行是我假設將更新相機與翻譯相反(y和z切換為我正在使用的格式)。 我是以錯誤的順序做的嗎?

這是我非常簡單的着色器:

#version 120

attribute vec4 position;
uniform mat4 camera;

void main()
{
    gl_Position = position * camera;
}

#version 120
void main(void)
{
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

這只是一個紅色三角形。 相機在三角形周圍旋轉,這不是我想要的。 我想讓它旋轉相機。 我認為將相機矩陣乘以每個頂點會在相機空間中進行渲染。 或者我還需要將它乘以投影矩陣?

移動w,a,s或d一下子變得非常接近,並且在整個視圖中扭曲整個視圖,到處都是紅色碎片。

以相反的順序編寫矩陣運算。 因此,如果要轉換(到相機位置)然后旋轉,請按以下順序寫入:

// Update our camera matrix
camMatrix = glm::rotate(glm::mat4(1.0f), anglePitch, glm::vec3(1, 0, 0));
camMatrix = glm::rotate(camMatrix, angleYaw, glm::vec3(0, 1, 0));
camMatrix = glm::translate(camMatrix, glm::vec3(-position.x, -position.z, -position.y));

暫無
暫無

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

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