Any better way to use keyEvent?



  • hi, i was trying too see how keypress librarie is :) so i first made something that increases posX on pressevents, but i didn't like the way that my ball moved, so i created this, but i don't feel like this is a good way to do this (resources ect, i know in here it just works but if i made a game or something that wouldn't be good)

    @
    void Game::keyPressEvent(QKeyEvent *event)
    {
    switch(event->key())
    {
    case Qt::Key_W:
    KW = true;
    break;
    case Qt::Key_S:
    KS = true;
    break;
    case Qt::Key_A:
    KA = true;
    break;
    case Qt::Key_D:
    KD = true;
    break;
    default:
    break;
    }
    }

    void Game::keyReleaseEvent(QKeyEvent *event)
    {
    switch(event->key())
    {
    case Qt::Key_W:
    KW = false;
    break;
    case Qt::Key_S:
    KS = false;
    break;
    case Qt::Key_A:
    KA = false;
    break;
    case Qt::Key_D:
    KD = false;
    break;
    default:
    break;
    }
    }

    void Game::mousePressEvent(QMouseEvent *event)
    {
    posY = event->y() - 25;
    posX = event->x() - 25;
    }

    void Game::timerEvent(QTimerEvent *e)
    {
    //-Y-
    if(KW == true)
    posY-=3;
    if(KS == true)
    posY+=3;

    //-X-
    if(KD == true)
        posX+=3;
    if(KA == true)
        posX-=3;
    
    if(posY > height() - 50)
        posY = height() -50;
    if(posY < 0)
        posY = 0;
    
    if(posX > width() - 50)
        posX = width() -50;
    if(posX < 0)
        posX = 0;
    
    repaint();
    

    }@

    is my code fine? or can you recommend me someother way !?



  • This post is deleted!

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.