I've been wondering how to work out the logic for creating smooth tile-based movement for a player.
These are the functions being used to handle player movement as of now. (Input and animation is already being handled, but not in the code. I just want to show the basics of how the logic works for now.)
void Player::startMovingUp() {
mVelocityY = -kWalkSpeed;
mDirectionFacing = UP;
}
void Player::startMovingDown() {
mVelocityY = kWalkSpeed;
mDirectionFacing = DOWN;
}
void Player::startMovingLeft() {
mVelocityX = -kWalkSpeed;
mDirectionFacing = LEFT;
}
void Player::startMovingRight() {
mVelocityX = kWalkSpeed;
mDirectionFacing = RIGHT;
}
void Player::stopMoving() {
mVelocityX = 0;
mVelocityY = 0;
}
All of these values are updated in the player update function. (Everything is time-based, rather than frame-based. That's where the elapsed_time_ms variable comes in.)
void Player::update(int elapsed_time_ms) {
mX += round(mVelocityX * elapsed_time_ms);
mY += round(mVelocityY * elapsed_time_ms);
}
This is perfectly fine to move the player around. But I want my player to be moving on a tiled map, locked to a grid, rather than just moving freely like this.
Each tile in the game have fixed dimensions of 16 by 16 pixels. This may be important, so I'm just leaving it here.