FInally have a working camera in the engine that can be controlled via both keyboard and mouse

This commit is contained in:
Warwick 2022-02-03 16:55:48 +00:00
parent 8539780043
commit 5811e13f55
No known key found for this signature in database
GPG key ID: A063045576839DB7
2 changed files with 34 additions and 2 deletions

View file

@ -15,6 +15,35 @@ void PlayerCamera::tick() {
// get position to look at // get position to look at
glm::vec3 cameraTarget = cameraPosition + cameraForward; glm::vec3 cameraTarget = cameraPosition + cameraForward;
// TODO Handle movement speed based on delta time
// handle keyboard input
const Uint8 *keyboardState = SDL_GetKeyboardState(nullptr);
if (keyboardState[SDL_SCANCODE_W])
cameraPosition += cameraForward * movementSpeed;
if (keyboardState[SDL_SCANCODE_S])
cameraPosition -= cameraForward * movementSpeed;
if (keyboardState[SDL_SCANCODE_A])
cameraPosition += cameraRight * movementSpeed;
if (keyboardState[SDL_SCANCODE_D])
cameraPosition -= cameraRight * movementSpeed;
// handle mouse
SDL_GetRelativeMouseState(&mouseX, &mouseY);
cameraYaw += mouseX * mouseSensitivity;
cameraPitch -= mouseY * mouseSensitivity;
// lock pitch to certain range
if (cameraPitch > 89.0f)
cameraPitch = 89.0f;
if (cameraPitch < -89.0f)
cameraPitch = -89.0f;
// calculate camera rotation
glm::vec3 direction;
direction.x = cos(glm::radians(cameraYaw)) * cos(glm::radians(cameraPitch));
direction.y = sin(glm::radians(cameraPitch));
direction.z = sin(glm::radians(cameraYaw)) * cos(glm::radians(cameraPitch));
cameraForward = glm::normalize(direction);
// MVP stuff // MVP stuff
glm::mat4 model = glm::mat4(1.0f); glm::mat4 model = glm::mat4(1.0f);

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include "Error.h" #include "Error.h"
#include <SDL2/SDL_keyboard.h>
#include <SDL2/SDL_mouse.h> #include <SDL2/SDL_mouse.h>
#include <SDL2/SDL_stdinc.h> #include <SDL2/SDL_stdinc.h>
#include <glm/glm.hpp> #include <glm/glm.hpp>
@ -12,13 +13,15 @@ private:
// Error reporting class // Error reporting class
Error error = Error("PlayerCamera"); Error error = Error("PlayerCamera");
// Constants for speed and sensitivity // Constants for speed and sensitivity
const float movementSpeed = 0.005f; const float movementSpeed = 0.02f;
const float mouseSensitivity = 0.005f; const float mouseSensitivity = 0.05f;
// Player position // Player position
glm::vec3 cameraPosition = glm::vec3(0.0f, 0.0f, 3.0f); glm::vec3 cameraPosition = glm::vec3(0.0f, 0.0f, 3.0f);
glm::vec3 cameraForward = glm::vec3(0.0f, 0.0f, -1.0f); glm::vec3 cameraForward = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 0.0f, -1.0f); glm::vec3 cameraUp = glm::vec3(0.0f, 0.0f, -1.0f);
float cameraYaw = -90.0f;
float cameraPitch = 0.0f;
// Mouse position // Mouse position
int mouseX, mouseY; int mouseX, mouseY;