Rotating a Open GL camera correctly using GLM - c++

I have a camera class, which is initialized like so:
CameraFP::CameraFP() {
this->aspect_ratio = 800.0f / 600.0f;
this->fov = 45.0f;
this->near_plane = 0.1f;
this->far_plane = 1000.0f;
this->position = glm::vec3(0, 0, 0);
this->target = position + glm::vec3(0, 0, -1);
this->up = glm::vec3(0, 1, 0);
this->m_rotation = glm::mat4(1.0);
m_view = glm::lookAt(position, target, up);
m_projection = glm::perspective(fov, aspect_ratio, near_plane, far_plane);
}
And here are other functions of import:
void CameraFP::update(sf::Window *app) {
process_keyboard(app);
process_mouse(app);
calculate_view();
}
void CameraFP::process_keyboard(sf::Window *app) {
const sf::Input *input = &app->GetInput();
up = m_rotation * glm::vec3(0, 1, 0);
glm::vec3 forward = glm::vec3(0, 0, -1);
glm::vec3 forward_rotated = m_rotation * forward;
glm::vec3 right = glm::vec3(1, 0, 0);
glm::vec3 right_rotated = m_rotation * right;
if (input->IsKeyDown(sf::Key::W)) {
position += forward_rotated;
}
if (input->IsKeyDown(sf::Key::S)) {
position -= forward_rotated;
}
if (input->IsKeyDown(sf::Key::A)) {
position -= right_rotated;
}
if (input->IsKeyDown(sf::Key::D)) {
position += right_rotated;
}
}
void CameraFP::process_mouse(sf::Window *app) {
// TODO: Make the below constants, and take framerate into account
GLfloat SPEED_X = 0.000001f;
GLfloat SPEED_Y = 0.000001f;
GLfloat mouse_x = app->GetInput().GetMouseX();
GLfloat mouse_y = app->GetInput().GetMouseY();
GLfloat mouse_x_delta = old_mouse_x - mouse_x;
GLfloat mouse_y_delta = old_mouse_y - mouse_y;
if (mouse_x_delta != 0 ||
mouse_y_delta != 0) {
if (mouse_x_delta != 0) {
y_rot += mouse_x_delta * SPEED_X;
m_rotation = glm::rotate(m_rotation, y_rot, glm::vec3(0, 1, 0));
}
if (mouse_y_delta != 0) {
x_rot += mouse_y_delta * SPEED_Y;
m_rotation = glm::rotate(m_rotation, x_rot, glm::vec3(1, 0, 0));;
}
}
this->old_mouse_x = mouse_x;
this->old_mouse_y = mouse_y;
app->SetCursorPosition(app->GetWidth() / 2, app->GetHeight() / 2);
}
void CameraFP::calculate_view() {
glm::vec3 forward = glm::vec3(0, 0, -1);
glm::vec3 forward_rotated = m_rotation * forward;
target = position += glm::normalize(forward_rotated);
m_view = glm::lookAt(position, target, up);
}
My problem is that when I compile the project, the compiler outputs an error saying:
\CameraFP.cpp|59|error: no match for 'operator*' in '((CameraFP*)this)->CameraFP::m_rotation * glm::detail::tvec3<float>(((const int&)((const int*)(&0))), ((const int&)((const int*)(&1))), ((const int&)((const int*)(&0))))'|
From what I understand vec = mat4 * vec should yield a rotated vector? Since I haven't been able to test this code, I don't know if the function work correctly.
Edit
Updated code according to the comments and awnsers. My problem is now that I get a BSOD, somewhere in the render function...
void CameraFP::process_keyboard(sf::Window *app) {
const sf::Input *input = &app->GetInput();
up = m_rotation * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f);
glm::vec4 forward = glm::vec4(0.0f, 0.0f, -1.0f, 0.0f);
glm::vec4 forward_rotated = m_rotation * forward;
glm::vec4 right = glm::vec4(1.0f, 0.0f, 0.0f, 0.0f);
glm::vec4 right_rotated = m_rotation * right;
if (input->IsKeyDown(sf::Key::W)) {
position += forward_rotated;
}
if (input->IsKeyDown(sf::Key::S)) {
position -= forward_rotated;
}
if (input->IsKeyDown(sf::Key::A)) {
position -= right_rotated;
}
if (input->IsKeyDown(sf::Key::D)) {
position += right_rotated;
}
}
void CameraFP::process_mouse(sf::Window *app) {
// TODO: Make the below constants, and take framerate into account
GLfloat SPEED_X = 0.000001f;
GLfloat SPEED_Y = 0.000001f;
GLfloat mouse_x = app->GetInput().GetMouseX();
GLfloat mouse_y = app->GetInput().GetMouseY();
GLfloat mouse_x_delta = old_mouse_x - mouse_x;
GLfloat mouse_y_delta = old_mouse_y - mouse_y;
if (mouse_x_delta != 0 ||
mouse_y_delta != 0) {
if (mouse_x_delta != 0) {
y_rot += mouse_x_delta * SPEED_X;
m_rotation = glm::rotate(m_rotation, y_rot, glm::vec3(0.0f, 1.0f, 0.0f));
}
if (mouse_y_delta != 0) {
x_rot += mouse_y_delta * SPEED_Y;
m_rotation = glm::rotate(m_rotation, x_rot, glm::vec3(1.0f, 0.0f, 0.0f));;
}
}
this->old_mouse_x = mouse_x;
this->old_mouse_y = mouse_y;
app->SetCursorPosition(app->GetWidth() / 2, app->GetHeight() / 2);
}
void CameraFP::calculate_view() {
glm::vec4 forward = glm::vec4(0.0f, 0.0f, -1.0f, 0.0f);
glm::vec4 forward_rotated = m_rotation * forward;
target = position += forward_rotated;
m_view = glm::lookAt(v4tov3(position), v4tov3(target), v4tov3(up));
}
glm::vec3 v4tov3(glm::vec4 v1) {
return glm::vec3(v1.x, v1.y, v1.z);
}
Edit 2
Problem now is with the camera rotation with the mouse, it just doesn't work, for some reason changes on the x axis oft times effect change on the y and vice versa. In addition, if I move the mouse right or left on the x axis (y rotation) the camera rotates left...
void CameraFP::process_mouse(sf::Clock *clock, sf::Window *app) {
// TODO: Make the below constants, and take framerate into account
GLfloat SPEED_X = 0.25f;
GLfloat SPEED_Y = 0.25f;
GLfloat screen_x = app->GetWidth();
GLfloat screen_y = app->GetHeight();
GLfloat mouse_x = float(screen_x / 2 - app->GetInput().GetMouseX());
GLfloat mouse_y = float(screen_y / 2 - app->GetInput().GetMouseY());
GLfloat mouse_x_delta = old_mouse_x - mouse_x;
GLfloat mouse_y_delta = old_mouse_y - mouse_y;
GLfloat current_time = clock->GetElapsedTime();
GLfloat delta_time = current_time - last_time;
this->last_time = current_time;
if (mouse_x_delta != 0 ||
mouse_y_delta != 0) {
if (mouse_x_delta != 0) {
y_rot += glm::radians(delta_time * SPEED_X * mouse_x);
m_rotation = glm::rotate(m_rotation, y_rot, glm::vec3(0.0f, 1.0f, 0.0f));
std::cout << "Y Rotation: " << y_rot << "\n";
}
if (mouse_y_delta != 0) {
x_rot += glm::radians(delta_time * SPEED_Y * mouse_y);
m_rotation = glm::rotate(m_rotation, x_rot, glm::vec3(1.0f, 0.0f, 0.0f));
std::cout << "X rotation: " << x_rot << "\n";
}
}
app->SetCursorPosition(screen_x / 2, screen_y / 2);
this->old_mouse_x = float(screen_x / 2 - app->GetInput().GetMouseX());
this->old_mouse_y = float(screen_y / 2 - app->GetInput().GetMouseY());
}

Replace all glm::vec3(0, 1, 0); by glm::vec3(0.0f, 1.0f, 0.0f);
As for the vec-mac multiplication, AquilaRapax is right in that you can only multiply a mat4 with a vec4. But since you're multiplying directions, the 4rth coordinate should be 0.0f, not 1.0f. This will have the effect to ignore the translations (1.0 will teke them into account, which you don't want)
See http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/ for details on matrices.
However, it's often a good idea to keep vec3 instead of vec4's, mostly for clarity purposes (i.e., glm::vec3 mPosition instead of glm::vec4 mPosition). It is thus handy to have 2 functions like these (untested) :
glm::vec3 TransformDirection(glm::vec3 pDirection, glm::mat4 pMatrix){
return pMatrix * glm::vec4(pDirection, 0.0f);
}
glm::vec3 TransformPosition(glm::vec3 pDirection, glm::mat4 pMatrix){
return pMatrix * glm::vec4(pDirection, 1.0f);
}

At the end of process::mouse you save the coordinates in old_mouse_x and old_mouse_y but then you move the cursor to the middle of the screen. If you do this old_mouse_x and old_mouse_y becomes invalid. What you need to do is set these variables after repositioning the cursor:
app->SetCursorPosition(app->GetWidth() / 2, app->GetHeight() / 2);
this->old_mouse_x = app->GetWidth() / 2;
this->old_mouse_y = app->GetHeight() / 2;

Related

OpenGL rotating an object around it's own axis

I am trying to rotate an object around its own x-axis. It works exactly as expected when it is on the right side of the y-axis but showcases strange behavior when it on the left.
void Animation::rotate_x(float degree) {
// get the position of the object wrt to origin
glm::vec3 position = glm::vec3(m_model_mat[3]);
glm::vec3 position_rev = -position;
// get the angle of the obj wrt y-axis
float angleY = atan2(m_model_mat[0][2], sqrt((m_model_mat[0][0] * m_model_mat[0][0]) + (m_model_mat[0][1] * m_model_mat[0][1])));
angleY = angleY * 180 / M_PI;
std::cout << angleY << "\n";
if(position[0] < 0){
if(angleY > 0){
angleY = 90 + angleY;
} else if (angleY < 0)
{
angleY = -90 + angleY;
} else{
angleY = 180;
}
}
std::cout << angleY << "\n";
// rotate so angle with y is 0
glm::mat4 rot_y_mat = glm::mat4(1.0f);
rot_y_mat = glm::rotate(rot_y_mat, glm::radians(-angleY), glm::vec3(0.0f, 1.0f, 0.0f));
// rotate to bring back to the correct position wrt y
glm::mat4 rev_rot_y_mat = glm::mat4(1.0f);
rev_rot_y_mat = glm::rotate(rev_rot_y_mat, glm::radians(angleY), glm::vec3(0.0f, 1.0f, 0.0f));
// rotate on x
glm::mat4 rotation_mat = glm::mat4(1.0f);
rotation_mat = glm::rotate(rotation_mat, glm::radians(degree), glm::vec3(1.0f, 0.0f, 0.0f));
// translate back to the original position
glm::mat4 trans_to_position = glm::mat4(1.0f);
trans_to_position = glm::translate(trans_to_position, position);
// move obj to origin
glm::mat4 trans_to_origin = glm::mat4(1.0f);
trans_to_origin = glm::translate(trans_to_origin, position_rev);
m_model_mat = trans_to_origin * m_model_mat;
m_model_mat = rev_rot_y_mat * m_model_mat;
m_model_mat = rotation_mat * m_model_mat;
m_model_mat = rot_y_mat * m_model_mat;
m_model_mat = trans_to_position * m_model_mat;
}
Here the m_model_mat is my object matrix which I am transforming.

What is the right way to update "front" vector with custom "world up" vector?

I am trying to implement "planet" world. So in any point on it's surface with my old camera class I got result like this :
Camera class update code is:
void cCamera::ProcessMouseMovement(GLdouble dt, glm::vec2 curOffset)
{
curOffset.x *= static_cast<GLfloat>(dt * m_MouseSensitivity);
curOffset.y *= static_cast<GLfloat>(dt * m_MouseSensitivity);
m_fPitch += curOffset.x;
m_fYaw += curOffset.y;
if (m_fYaw > 89.0f)
m_fYaw = 89.0f;
if (m_fYaw < -89.0f)
m_fYaw = -89.0f;
UpdateCameraVectors();
}
void cCamera::UpdateCameraVectors(void)
{
float fYawRad = glm::radians(m_fYaw);
float fPitchRad = glm::radians(m_fPitch);
float fYawCos = cos(fYawRad);
glm::vec3 front { cos(fPitchRad) * fYawCos,
sin(fYawRad),
sin(fPitchRad) * fYawCos };
*m_pCameraFront = glm::normalize(front);
m_Right = glm::normalize(glm::cross(*m_pCameraFront, m_WorldUp));
m_Up = glm::normalize(glm::cross(m_Right, front));
*m_pViewMatrix = glm::lookAt(glm::vec3(0.f), glm::vec3(0.f) + *m_pCameraFront, m_Up);
}
As (0,0,0) is planet center, I suppose I should udate m_WorldUp vector this way:
m_WorldUp = glm::normalize(*m_pPos);
And indeed, the results are good: camera turned the right way, but it's rotation is broken. Yaw and pitch are still dependent on old world up. I think, I should update front vector with new m_WorldUp, but don't really know how.
Solution was found here: https://gamedev.stackexchange.com/questions/73588/how-do-i-fix-my-planet-facing-camera
In my case code is
void cCamera::UpdateCameraVectors(void)
{
m_WorldUp = glm::normalize(*m_pPos);
glm::quat world_axes_rotation = glm::angleAxis(glm::radians(m_fPitch), glm::vec3(0.0f, -1.0f, 0.0f));
world_axes_rotation = glm::normalize(world_axes_rotation);
world_axes_rotation = glm::rotate(world_axes_rotation, glm::radians(m_fYaw), glm::vec3(1.0f, 0.0f, 0.0f));
m_Pole = glm::normalize(m_Pole - glm::dot(m_WorldUp, m_Pole) * m_WorldUp);
glm::mat4 local_transform;
local_transform[0] = glm::vec4(m_Pole, 0.0f);
local_transform[1] = glm::vec4(m_WorldUp, 0.0f);
local_transform[2] = glm::vec4(glm::cross(m_Pole, m_WorldUp), 0.0f);
local_transform[3] = glm::vec4(0.f, 0.f, 0.f, 1.0f);
world_axes_rotation = glm::normalize(world_axes_rotation);
*m_pViewMatrix = local_transform * glm::mat4_cast(world_axes_rotation);
*m_pCameraFront = -1.0f * glm::vec3((*m_pViewMatrix)[2]);
m_Up = glm::vec3((*m_pViewMatrix)[1]);
m_Right = glm::vec3((*m_pViewMatrix)[0]);
*m_pViewMatrix = glm::inverse(*m_pViewMatrix);
}

Pool Game physics velocity calculation issue

Hi I am making a 3d pool game and I am currently at the state of applying collisions, I am using openGL and C++. I already have the collision written and it is working properly. The issue I have is related only to the velocity of the ball class and passing forces to other balls on collision.
I have a ball class that is used for all the balls including the cue ball. I have a drawBall() function:
void drawBall(Shader ourShader) {
extern GLfloat deltaTime;
a = F / radius;
v = v + (a * deltaTime);
ballPos = ballPos + (v*deltaTime) + (0.5f*a*deltaTime*deltaTime);
collision();
//F = glm::vec3(0.0f, 0.0f, 0.0f);
//ACTUAL DRAWING
glBindVertexArray(VAO);
glm::mat4 model;
model = glm::translate(model, ballPos);
model = glm::rotate(model, glm::radians(40.0f), glm::vec3(1.0f, 0.0f, 0.0f));
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
And a collision function:
void collision() {
extern vector <Ball> ballCollection;
for (int i = 0; i < ballCollection.size(); i++) {
if (glm::distance(ballCollection.at(i).ballPos, ballPos) <= (2 * radius)) {
if (!glm::distance(ballCollection.at(i).ballPos, ballPos) == 0) {
extern GLfloat forceAmount;
if (isColliding == 0) {
glm::vec3 collPoint = glm::vec3((ballPos.x + ballCollection.at(i).ballPos.x) / 2, 0.0f, (ballPos.z + ballCollection.at(i).ballPos.z) / 2);
glm::vec3 collPointPerp = collPoint - ballPos;
glm::vec3 otherNew = collPointPerp;
glm::vec3 thisNew = glm::cross(collPointPerp, glm::vec3(0.0, 1.0, 0.0));
F = thisNew;
ballCollection.at(i).F = otherNew;
glm::vec3 newV;
glm::vec3 otherNewV;
newV.x = (v.x * (2 * ballCollection.at(i).radius * ballCollection.at(i).v.x)) / (radius + ballCollection.at(i).radius);
newV.z = (v.z * (2 * ballCollection.at(i).radius * ballCollection.at(i).v.z)) / (radius + ballCollection.at(i).radius);
newV.y = 0.0f;
otherNewV.x = (ballCollection.at(i).v.x * (2 * radius * v.x)) / (radius + ballCollection.at(i).radius);
otherNewV.z = (ballCollection.at(i).v.z * (2 * radius * v.z)) / (radius + ballCollection.at(i).radius);
otherNewV.y = 0.0f;
v.x = newV.x;
v.z = newV.z;
ballCollection.at(i).v.x = otherNewV.x;
ballCollection.at(i).v.z = otherNewV.z;
}
isColliding = 1;
ballCollection.at(i).isColliding = 1;
}
}
}
isColliding = 0;
This calss is in a separate file, in my main cpp. This has a key_kallback function:
void do_movement()
{
glm::vec3 cameraRight = glm::normalize(glm::cross(cameraFront, cameraUp));
GLfloat cameraSpeed = 50.0f;
glm::vec3 aboveBall = glm::vec3(ballCollection.at(15).ballPos.x, ballCollection.at(15).ballPos.y + 20.0f, ballCollection.at(15).ballPos.z);
glm::vec3 cameraFwd = aboveBall - cameraPos;
//cout << cameraFwd.x << "," << cameraFwd.y << "," << cameraFwd.z << endl;
if (keys[GLFW_KEY_W])
ballCollection.at(15).ballPos = ballCollection.at(15).ballPos + glm::vec3(0.0f, 0.0f, -0.1f);
if (keys[GLFW_KEY_S])
ballCollection.at(15).ballPos = ballCollection.at(15).ballPos + glm::vec3(0.0f, 0.0f, 0.1f);
if (keys[GLFW_KEY_A])
ballCollection.at(15).ballPos = ballCollection.at(15).ballPos + glm::vec3(-0.1f, 0.0f, 0.0f);
if (keys[GLFW_KEY_D])
ballCollection.at(15).ballPos = ballCollection.at(15).ballPos + glm::vec3(0.1f, 0.0f, 0.0f);
if (keys[GLFW_KEY_SPACE]) {
ballCollection.at(15).F = 10.0f*glm::normalize(cameraFwd);
}
if (keys[GLFW_KEY_E]) {
ballCollection.at(15).F = -10.0f * glm::normalize(cameraFwd);
}
}
And then within the game loop:
for (int i = 0; i < 16; i++) {
ballCollection.at(i).drawBall(ourShader);
}
cameraPos = ballCollection.at(15).ballPos + glm::vec3(0.0f, 20.0f, 20.0f);
do_movement();
My problem is that when I apply the force to the cue ball with space, since the F value keeps adding to v, my cue ball speed increases every frame. If I put F back to 0 after applying the force, I can't pass force to other balls, therefore their v is 0 and they don't move after collision.
Any help would be very appreciated, please comment if I there is extra information needed.
EDIT
I realized that I had an error in the collision calculation, it should be:
newV.x = (v.x + (2 * ballCollection.at(i).radius * ballCollection.at(i).v.x)) / (radius + ballCollection.at(i).radius);
newV.z = (v.z + (2 * ballCollection.at(i).radius * ballCollection.at(i).v.z)) / (radius + ballCollection.at(i).radius);
newV.y = 0.0f;
otherNewV.x = (ballCollection.at(i).v.x + (2 * radius * v.x)) / (radius + ballCollection.at(i).radius);
otherNewV.z = (ballCollection.at(i).v.z + (2 * radius * v.z)) / (radius + ballCollection.at(i).radius);
otherNewV.y = 0.0f;
Now, if I make F back to zero in the class after calculations, the ball moves with constant velocity which is fine for now. My issue now is that sometimes the collision works, sometimes the balls fly away, sometimes hitting the first ball is fine but if the second ball hits another one then its wrong again. I think this happens because they keep colliding and calculating their speed wrong, but I can't figure out how to set up a boolean to collide only once, anyone have any idea?
EDIT
I managed to set up the boolean correctly now.
On collision, the force that should be applied to the other ball is the magnitude of the velocity vector. So if you pass in sqrt(v.x*v.x+v.y*v.y+v.z*v.z) as the initial force of the collision and set F to zero after applying the force like you stated, you should get the results you desire.

Calculation for View Matrix in C++ DirectX 9

I'm trying to create a first-person shooter camera for my DirectX game. But I'm struggling in trying to get my view matrix right. At the moment I have only got a triangle to display on the screen, but when I rotate the camera and move forward it seems like the triangle is rotating around the camera instead. Here is the code I have done for the Camera Class
Camera.h
#pragma once
#include"Window.h"
#include"Matrix.h"
#include "Vector3.h"
class Camera
{
public:
Camera();
Camera(float pitch, float yaw, Vector3 position);
~Camera();
void Update();
D3DXMATRIX BuildViewMatrix();
Vector3 GetPosition() const { return position; }
void SetPosition(Vector3 val) { position = val; }
protected:
float yaw;
float pitch;
Vector3 position;
};
Camera.cpp
#include"Camera.h"
Camera::Camera()
{
yaw = 0.0f;
pitch = 0.0f;
}
Camera::Camera(float pitch, float yaw, Vector3 position)
{
this->pitch = pitch;
this->yaw = yaw;
this->position = position;
}
Camera::~Camera()
{
}
void Camera::Update()
{
pitch = min(pitch, 90.0f);
pitch = max(pitch, -90.0f);
if(yaw < 0)
yaw += 360.0f;
if( yaw > 360.0f)
yaw -= 360.0f;
if(Window::GetKeyboard()->KeyDown(KEYBOARD_W))
{
D3DXMATRIX translateMat;
D3DXMatrixTranslation(&translateMat, position.x, position.y, position.z);
D3DXMATRIX rotationMat;
D3DXMatrixRotationY(&rotationMat, D3DXToRadian(yaw));
D3DXMATRIX forwardMat;
D3DXMatrixTranslation(&forwardMat, 0.0f, 0.0f, 10.0f);
D3DXMATRIX transformMat = translateMat * rotationMat * forwardMat;
position.x = transformMat._41;
position.y = transformMat._42;
position.z = transformMat._43;
std::cout << "X: " << transformMat._41 << std::endl;
std::cout << "Y: " << transformMat._42 << std::endl;
std::cout << "Z: " << transformMat._43 << std::endl;
}
else if(Window::GetKeyboard()->KeyDown(KEYBOARD_S))
{
D3DXMATRIX translateMat;
D3DXMatrixTranslation(&translateMat, position.x, position.y, position.z);
D3DXMATRIX rotationMat;
D3DXMatrixRotationY(&rotationMat, D3DXToRadian(yaw));
D3DXMATRIX forwardMat;
D3DXMatrixTranslation(&forwardMat, 0.0f, 0.0f, -10.0f);
D3DXMATRIX transformMat = translateMat * rotationMat * forwardMat;
position.x = transformMat._41;
position.y = transformMat._42;
position.z = transformMat._43;
std::cout << "X: " << transformMat._41 << std::endl;
std::cout << "Y: " << transformMat._42 << std::endl;
std::cout << "Z: " << transformMat._43 << std::endl;
}
if(Window::GetKeyboard()->KeyDown(KEYBOARD_Q))
{
yaw = yaw - 1.0f;
}
if(Window::GetKeyboard()->KeyDown(KEYBOARD_E))
{
yaw = yaw + 1.0f;
}
}
D3DXMATRIX Camera::BuildViewMatrix()
{
D3DXMATRIX translationMat;
D3DXMatrixTranslation(&translationMat, (position.x * -1.0f), (position.y * -1.0f), (position.z * -1.0f));
D3DXMATRIX yawMat;
D3DXMatrixRotationY(&yawMat, D3DXToRadian((yaw * -1.0f)));
D3DXMATRIX pitchMat;
D3DXMatrixRotationX(&pitchMat, D3DXToRadian((pitch * -1.0f)));
D3DXMATRIX viewMat = pitchMat * yawMat * translationMat;
return viewMat;
}
I'm using device->SetTransform(D3DTS_VIEW, &camera->BuildViewMatrix()); to send the view matrix to directX. What exactly am I doing wrong? Please help
UPDATE:
I have change the code and tried to use the D3DXMatrixLookAtLH function (doesn't use the Camera at all), but this time, it doesn't do anything - the triangle stays in the same position no matter how I change the LookAt parameter on the function. Here is the code for it:
void Renderer::Render()
{
device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(40, 40, 40), 1.0f, 0);
device->BeginScene(); //Must be used as it tells DirectX we're starting to draw stuff.
D3DXMATRIX worldMat;
D3DXMatrixTranslation(&worldMat, 0.0f, 0.0f, 0.0f);
device->SetTransform(D3DTS_WORLD, &worldMat);
D3DXMATRIX viewMatrix;
D3DXMatrixLookAtLH( &viewMatrix,
&D3DXVECTOR3(0.0f, -100.0f, 1000.0f), //position
&D3DXVECTOR3(0.0f, 1.0f, 0.0f), //Look at
&D3DXVECTOR3(0.0f, 1.0f, 0.0f));
device->SetTransform(D3DTS_VIEW, &viewMatrix);
//device->SetTransform(D3DTS_VIEW, &camera->BuildViewMatrix());
D3DXMATRIX projMatrix;
D3DXMatrixPerspectiveFovLH( &projMatrix,
D3DXToRadian(45),
(float)width/(float)height,
1.0f,
10000.0f);
device->SetTransform(D3DTS_PROJECTION, &projMatrix);
device->SetFVF(VERTEXFORMAT);
device->SetStreamSource(0, vertexBuffer, 0, sizeof(VERTEX));
device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
device->EndScene(); //Thank you for waiting, I have finished drawing stuff on the screen, please handle the rest Mr DirectX.
device->Present(NULL, NULL, NULL, NULL);
}
Found out the problem, the matrices I've calculated isn't correct as well as the view matrix. the fixed it by adding the following codes:
Camera.h
#pragma once
#pragma comment(lib, "d3dx9.lib")
#include<d3dx9math.h>
#include"Window.h"
class Camera
{
public:
Camera();
Camera(float pitch, float yaw, D3DXVECTOR3 position);
~Camera();
void Update();
D3DXMATRIX BuildViewMatrix();
inline D3DXVECTOR3 GetPosition() const { return position; }
inline void SetPosition(D3DXVECTOR3 position){ this->position = position;}
protected:
float yaw;
float pitch;
float roll;
D3DXVECTOR3 position;
private:
D3DXVECTOR3 xAxis;
D3DXVECTOR3 yAxis;
D3DXVECTOR3 zAxis;
};
Camera.cpp
#include"Camera.h"
Camera::Camera()
{
yaw = 0.0f;
pitch = 0.0f;
roll = 0.0f;
}
//yaw = head twist
//pitch = head tilt
Camera::Camera(float pitch, float yaw, D3DXVECTOR3 position)
{
this->pitch = pitch;
this->yaw = yaw;
roll = 0.0f;
this->position = position;
xAxis = D3DXVECTOR3(1.0f, 0.0f, 0.0f);
yAxis = D3DXVECTOR3(0.0f, 1.0f, 0.0f);
zAxis = D3DXVECTOR3(0.0f, 0.0f, 1.0f);
}
Camera::~Camera()
{
}
void Camera::Update()
{
if(Window::GetKeyboard()->KeyDown(KEYBOARD_Q)){
yaw -= 1.0f;
}
else if(Window::GetKeyboard()->KeyDown(KEYBOARD_E)){
yaw += 1.0f;
}
if(Window::GetKeyboard()->KeyDown(KEYBOARD_Z)){
pitch += 1.0f;
}
else if(Window::GetKeyboard()->KeyDown(KEYBOARD_X)){
pitch -= 1.0f;
}
pitch = min(pitch, 90.0f);
pitch = max(pitch, -90.0f);
if(yaw < 0.0f)
yaw += 360.0f;
if( yaw > 360.0f)
yaw -= 360.0f;
D3DXMATRIX yawMat;
D3DXMatrixRotationAxis(&yawMat, &yAxis, D3DXToRadian(yaw));
D3DXVec3TransformCoord(&zAxis, &zAxis, &yawMat);
D3DXVec3TransformCoord(&xAxis, &xAxis, &yawMat);
D3DXMATRIX pitchMat;
D3DXMatrixRotationAxis(&pitchMat, &xAxis, D3DXToRadian(pitch));
D3DXVec3TransformCoord(&zAxis, &zAxis, &pitchMat);
D3DXVec3TransformCoord(&yAxis, &yAxis, &pitchMat);
D3DXMATRIX rollMat;
D3DXMatrixRotationAxis(&rollMat, &zAxis, D3DXToRadian(0.0f));
D3DXVec3TransformCoord(&xAxis, &xAxis, &rollMat);
D3DXVec3TransformCoord(&yAxis, &yAxis, &rollMat);
if(Window::GetKeyboard()->KeyDown(KEYBOARD_W))
{
position = position + (zAxis * -1) * 10.0f;
}
else if(Window::GetKeyboard()->KeyDown(KEYBOARD_S))
{
position = position + zAxis * 10.0f;
}
if(Window::GetKeyboard()->KeyDown(KEYBOARD_A))
{
position = position + xAxis * 10.0f;
}
else if(Window::GetKeyboard()->KeyDown(KEYBOARD_D))
{
position = position - xAxis * 10.0f;
}
yaw = 0.0f;
pitch = 0.0f;
roll = 0.0f;
}
D3DXMATRIX Camera::BuildViewMatrix()
{
D3DXMATRIX viewMatrix;
D3DXMatrixIdentity(&viewMatrix);
viewMatrix._11 = xAxis.x;
viewMatrix._21 = xAxis.y;
viewMatrix._31 = xAxis.z;
viewMatrix._12 = yAxis.x;
viewMatrix._22 = yAxis.y;
viewMatrix._32 = yAxis.z;
viewMatrix._13 = zAxis.x;
viewMatrix._23 = zAxis.y;
viewMatrix._33 = zAxis.z;
viewMatrix._41 = D3DXVec3Dot(&position, &xAxis);
viewMatrix._42 = D3DXVec3Dot(&position, &yAxis);
viewMatrix._43 = D3DXVec3Dot(&position, &zAxis);
return viewMatrix;
}

Creating a First Person camera in Open GL 2.0 and glm

I am farly new to Open GL, and c++ and have come across the issue of creating a first person camera. I don't understand matrix math so that makes it all the more harder for me. So far, for calculating the rotation of the camera I have gone for this:
void CameraFP::calculate_view() {
m_view = glm::rotate(m_view, this->get_rotation_x(), glm::vec3(1, 0, 0));
m_view = glm::rotate(m_view, this->get_rotation_y(), glm::vec3(0, 1, 0));
}
That function is called every update call.
For handling the rotation of the camera via the mous, I've done the following:
void CameraFP::process_mouse(sf::Window *app) {
GLfloat mouse_x = app->GetInput().GetMouseX();
GLfloat mouse_y = app->GetInput().GetMouseY();
GLfloat mouse_x_delta = std::max(mouse_x, old_mouse_x) - std::min(mouse_x, old_mouse_x);
GLfloat mouse_y_delta = std::max(mouse_y, old_mouse_y) - std::min(mouse_y, old_mouse_y);
y_rot += mouse_x_delta / (float)app->GetWidth();
x_rot += mouse_y_delta / (float)app->GetHeight();
this->old_mouse_x = mouse_x;
this->old_mouse_y = mouse_y;
app->SetCursorPosition(app->GetWidth() / 2, app->GetHeight() / 2);
}
and for handling the movement I've done the following:
void CameraFP::process_keyboard(sf::Window *app) {
const sf::Input *input = &app->GetInput();
if (input->IsKeyDown(sf::Key::W)) {
position.z += 1.0f / 100.0f;
}
if (input->IsKeyDown(sf::Key::S)) {
position.z -= 1.0f / 100.0f;
}
if (input->IsKeyDown(sf::Key::A)) {
position.x -= 1.0f / 100.0f;
}
if (input->IsKeyDown(sf::Key::D)) {
position.x += 1.0f / 100.0f;
}
}
My issues lie in the fact that my camera does not move in the direction you face, and that it never stops rotating :/. Also, if you could point me to a guide or something on Matrix math that would be awesome :)
Edit 2:'
I just started a new process mouse function, and it a movement along the x axis of the screen as a y rotation for the camera correctly. However, it doesn't matter if I move the mouse left or right, both movements rotate me right. Same with the x axis in 3d space, but this happens downwards. Any ideas on what is causing this?
void CameraFP::process_mouse(sf::Window *app) {
GLfloat mouse_x = app->GetInput().GetMouseX();
GLfloat mouse_y = app->GetInput().GetMouseY();
GLfloat mouse_x_delta = old_mouse_x - mouse_x;
GLfloat mouse_y_delta = old_mouse_y - mouse_y;
if (mouse_x_delta > 0) {
y_rot += mouse_x_delta / (float)app->GetWidth() * 0.1f;
} else if (mouse_x_delta < 0) {
y_rot -= mouse_x_delta / (float)app->GetWidth() * 0.1f;
}
if (mouse_y_delta > 0) {
x_rot += mouse_y_delta / (float)app->GetWidth() * 0.1f;
} else if (mouse_y_delta < 0) {
x_rot -= mouse_y_delta / (float)app->GetWidth() * 0.1f;
}
if (mouse_x != old_mouse_x) {
m_view = glm::rotate(m_view, y_rot, glm::vec3(0, 1, 0));
}
if (mouse_y != old_mouse_y) {
m_view = glm::rotate(m_view, x_rot, glm::vec3(1, 0, 0));
}
this->old_mouse_x = mouse_x;
this->old_mouse_y = mouse_y;
app->SetCursorPosition(app->GetWidth() / 2, app->GetHeight() / 2);
}
I don't have time to look for my camera code at the moment, but what I can tell you right now is, that your movement calculation is simply wrong. You aren't taking the camera rotation into account.
You have to do something like this:
if (input->IsKeyDown(sf::Key::W)) {
position.z += sin(camera_rot_y);
}
else if (input->IsKeyDown(sf::Key::S)) {
position.z -= sin(camera_rot_y);
}
if (input->IsKeyDown(sf::Key::A)) {
position.x -= cos(camera_rot_y);
}
else if (input->IsKeyDown(sf::Key::D)) {
position.x += cos(camera_rot_y);
}
Also you can use "else if"s, because you cannot move forward and backward at the same time.^^
Also, why are you using std::min() and max() in the following code?:
GLfloat mouse_x_delta = std::max(mouse_x, old_mouse_x) - std::min(mouse_x, old_mouse_x);
GLfloat mouse_y_delta = std::max(mouse_y, old_mouse_y) - std::min(mouse_y, old_mouse_y);
If you want to rotate in the opposite direction you need to get a negative delta, which is impossible with your code. Get rid of the min() and max() functions.
BTW: My camera code is not the most efficient (uses rotate instead of direct calculations), but it works.
You didn't show usage of position in CameraFP and m_view but I think problem si here:
void CameraFP::process_keyboard(sf::Window *app) {
const sf::Input *input = &app->GetInput();
if (input->IsKeyDown(sf::Key::W)) {
position.z += 1.0f / 100.0f;
}
if (input->IsKeyDown(sf::Key::S)) {
position.z -= 1.0f / 100.0f;
}
if (input->IsKeyDown(sf::Key::A)) {
position.x -= 1.0f / 100.0f;
}
if (input->IsKeyDown(sf::Key::D)) {
position.x += 1.0f / 100.0f;
}
}
You must multiply matrix, with this translation, and m_view. In matrix multiplication is important order of matrices. First must be m_view because it is main matrix, and you want move forward from m_view rotation. But there is glm namespace and there is method glm::translate which them multiply in right order and you just create glm::vec3 as parameter of that method (translation with x, y, z).
(If you use relative position ... only difference between frames)
So you must change it like this:
void CameraFP::process_keyboard(sf::Window *app) {
const sf::Input *input = &app->GetInput();
glm::vec3 pos;
if (input->IsKeyDown(sf::Key::W)) {
pos.z += 1.0f / 100.0f;
}
if (input->IsKeyDown(sf::Key::S)) {
pos.z -= 1.0f / 100.0f;
}
if (input->IsKeyDown(sf::Key::A)) {
pos.x -= 1.0f / 100.0f;
}
if (input->IsKeyDown(sf::Key::D)) {
pos.x += 1.0f / 100.0f;
}
//Make translation
m_view = glm::translate(m_view, pos);
//Values at position 12, 13, 14 are translation x, y, z
//Save absolute position of camera
position = glm::vec3(m_view[12], m_view[13], m_view[14]);
}
PS: Sorry for my poor english.