简体   繁体   中英

The better way to control player in 2d game ? (sdl2)

I'm doing this like this, in .hpp file:

class Player
{
public:
    Player(){}
    Player(){}
    virtual ~Player(){}

    void handler(SDL_Event event);
    void update()
    {
        move(velocityForwardX, velocityForwardY); 
        move(-velocityBackwardX, -velocityBackwardY);
        /* the player moves from it current position. */
    }
protected:
    int speed = 5;
    int velocityForwardX = 0;
    int velocityForwardY = 0;
    int velocityBackwardX = 0;
    int velocityBackwardY = 0;

};

in .cpp file:

#include "Player.h"
void Player::handler(SDL_Event event)
{
if(event.type == SDL_KEYDOWN){
    switch(event.key.keysym.sym)
    {
    case SDLK_d:
        velocityForwardX = speed;
        break;
    case SDLK_q:
        velocityBackwardX = speed;
        break;
    case SDLK_z:
        velocityBackwardY = speed;
        break;
    case SDLK_s:
        velocityForwardY = speed;
        break;
    default:
        break;
    }
}
else if(event.type == SDL_KEYUP){
    switch(event.key.keysym.sym)
    {
    case SDLK_d:
        velocityForwardX = 0;
        break;
    case SDLK_q:
        velocityBackwardX = 0;
        break;
    case SDLK_z:
        velocityBackwardY = 0;
        break;
    case SDLK_s:
        velocityForwardY = 0;
        break;
    default:
        break;
    }
}}

like this I can presse any key and release it and the player move well. It also works if two opposite keys are pressed then one is release so the player is going in the right direction. Can we make it easier ? (sorry for my english)

You could store only one variable per direction and add and subtract speed when pressing and releasing a button, eg

    switch(event.key.keysym.sym)
    {
    case SDLK_d:
        velocityX += speed;
        break;
    case SDLK_q:
        velocityX -= speed;
        break;
    case SDLK_z:
        velocityY -= speed;
        break;
    case SDLK_s:
        velocityY += speed;
        break;
    default:
        break;
    }
    // similar for key release

With this if you press opposite x direction keys simultaniously, velocityX will be 0 , and the same for the y direction and velocityY .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM