Hello all, I'm a newbie here. I haven't programmed in many years, and I wanted to make a very simple platform game. My other code works as intended, and I've included the relevant section below.
In the code I have so far, I use WASD to control movement, with Shift to make the sprite move faster on the X axis. Movement on the Y axis works as intended.
The problem is that the X axis will not work unless I first press A or D (for left or right) and
then hold W or S. Once I hold A + W || S or D + W || S, the sprite moves. Shift works normally regardless.
In my debugging, I found that the boolean values are passed from handleMovement to the general update function. However, it only recognizes that the X axis values are passed if W or S is pressed as well. I'm quite frankly stumped, as this should be a fairly simple algorithm.
Any help would be greatly appreciated!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#include "Player.h"
#include "SDL.h"
Player::Player(const LoaderParams* pParams) : SDLGameObject(pParams){}
// draws the sprite
void Player::draw(){ SDLGameObject::draw(); }
// asks for the keyboard state, then updates the position
void Player::update(){
handleInput();
if(m_bMoveLeft){
if(m_bRunning){
m_velocity.m_x = -5;
}
else {
m_velocity.m_x = -2;
}
} else if(m_bMoveRight){
if(m_bRunning){
m_velocity.m_x = 5;
}
else {
m_velocity.m_x = 2;
}
} else if(m_bMoveUp){
m_velocity.m_y = -5;
} else if (m_bMoveDown){
m_velocity.m_y = 5;
}
else {
m_velocity.m_x = 0;
m_velocity.m_y = 0;
}
handleMovement(m_velocity);
m_currentFrame = 0;
SDLGameObject::update();
}
// invokes the Vector class to calculate movement
void Player::handleMovement(Vector2D velocity){
Vector2D newPos = m_position;
newPos.m_x = m_position.m_x + m_velocity.m_x;
newPos.m_y = m_position.m_y + m_velocity.m_y;
m_position = newPos;
}
// dummy function, no use yet
void Player::clean(){}
// checks to see which button, if any, is held down
// it sets a movement flag to off or on
void Player::handleInput(){
if(TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_D)){
m_bMoveLeft = false;
m_bMoveRight = true;
} else if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_A)){
m_bMoveRight = false;
m_bMoveLeft = true;
}
if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_W)){
m_bMoveUp = true;
m_bMoveDown = false;
} else if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_S)){
m_bMoveUp = false;
m_bMoveDown = true;
}
// default, sets all movement flags to OFF
else {
m_bMoveLeft = false;
m_bMoveRight = false;
m_bMoveUp = false;
m_bMoveDown = false;
}
// checks to see if SHIFT is held down to run
if(TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LSHIFT)){
m_bRunning = true;
} else { m_bRunning = false; }
}
|