Hi, I'm following this sdl tutorial by lazyfoo and i want to add a simple jump, like jumping 160px. Here the code for movement;
void Player::handleEvent(SDL_Event& e)
{
if (e.type == SDL_KEYDOWN && e.key.repeat == 0)
{
switch (e.key.keysym.sym)
{
case SDLK_UP: _velY -= _playerVel; break;
case SDLK_DOWN: _velY += _playerVel; break;
case SDLK_LEFT: _velX -= _playerVel; break;
case SDLK_RIGHT: _velX += _playerVel; break;
}
}
else if (e.type == SDL_KEYUP && e.key.repeat == 0)
{
switch (e.key.keysym.sym)
{
case SDLK_UP: _velY += _playerVel; break;
case SDLK_DOWN: _velY -= _playerVel; break;
case SDLK_LEFT: _velX += _playerVel; break;
case SDLK_RIGHT: _velX -= _playerVel; break;
}
}
}
void Player::move(std::vector<vec3Struct>& _levelInfo)
{
_posX += _velX;
if( ( _posX < 0 ) || ( _posX + _playerBox > 1000 /*levelWidth*/ ) || touchesWall(_levelInfo))
{
_posX -= _velX;
}
_posY += _velY;
if( touchesWall(_levelInfo))
{
_posY -= _velY;
}
}
bool Player::checkCollision( SDL_Rect a, SDL_Rect b )
{
//The sides of the rectangles
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//Calculate the sides of rect A
leftA = a.x;
rightA = a.x + a.w;
topA = a.y;
bottomA = a.y + a.h;
//Calculate the sides of rect B
leftB = b.x;
rightB = b.x + b.w;
topB = b.y;
bottomB = b.y + b.h;
//If any of the sides from A are outside of B
if( bottomA <= topB ) { return false; }
if( topA >= bottomB ) { return false; }
if( rightA <= leftB ) { return false; }
if( leftA >= rightB ) { return false; }
//If none of the sides from A are outside B
return true;
}
bool Player::touchesWall(std::vector<vec3Struct>& _levelInfo)
{
//Go through the tiles
for( int i = 0; i < _levelInfo.size(); ++i )
{
SDL_Rect tmp;
tmp.x = _levelInfo[i].x;
tmp.y = _levelInfo[i].y;
tmp.w = 80;
tmp.h = 80;
SDL_Rect _playerRec;
_playerRec.x = _posX;
_playerRec.y = _posY;
_playerRec.w = _playerBox;
_playerRec.h = _playerBox;
//If the collision box touches the wall tile
if( checkCollision( _playerRec, tmp) )
{
return true;
}
}
//If no wall tiles were touched
return false;
}
but everytime a try too add gravity to game, like if player is not toches wall, it y axis will decrease, but i always failed :(