Skip to content

Tutorial part 2 : Player movement

linuxlight edited this page Jun 8, 2021 · 4 revisions

Now we are going to implement player movement. Add checkKey() and checkMove() functions to Game.

Game.h

    void checkKey() override;
    void checkMove(Object& obj);

Game.cpp

void Game::checkKey()
{
    checkMove(*player);
}

// Implementation of KeyListener
void Game::checkMove(Object& obj)
{
    if (getKeyListener().keycheck(EAG_VKEY_UP)) {
        obj.rigidbody.setVelocity(0, -2);
        if (getKeyListener().keycheck(EAG_VKEY_LEFT))
            obj.rigidbody.setVelocity(-2, -2);
        else if (getKeyListener().keycheck(EAG_VKEY_RIGHT))
            obj.rigidbody.setVelocity(2, -2);
    }
    else if (getKeyListener().keycheck(EAG_VKEY_DOWN)) {
        obj.rigidbody.setVelocity(0, 2);
        if (getKeyListener().keycheck(EAG_VKEY_LEFT))
            obj.rigidbody.setVelocity(-2, 2);
        else if (getKeyListener().keycheck(EAG_VKEY_RIGHT))
            obj.rigidbody.setVelocity(2, 2);
    }
    else if (getKeyListener().keycheck(EAG_VKEY_LEFT)) {
        obj.rigidbody.setVelocity(-2, 0);
    }
    else if (getKeyListener().keycheck(EAG_VKEY_RIGHT)) {
        obj.rigidbody.setVelocity(2, 0);
    }
    else {
        obj.rigidbody.setVelocity(0, 0);
    }
}

If you set velocity for object, the object will move by its velocity. But, if you compile and run, player won't move. It's because you didn't call function Object::move(). But, Object.move needs paramater of other objects to detect collision before moving.

Object.move(vector<Object*> objects)

Hence, we will make vector of objects that participate in a game.


In class game_loop, vector of Object* is already declared. So, we will use that to store player and boundary.
Add following sentences to Game::initialize() :

objects.push_back(boundary);
objects.push_back(player);

Now, add player movement before drawing the objects.

void Game::updateLoop()
{
    player->move(objects);

    getConsole().drawTmpObject(*player);
    getConsole().drawTmpObject(*boundary);
}

Player will move!!
Next time, we will implement shooting.