Reputation: 95
I have done a map with Tiled. Every single tile of it measures 32x32 px
so does my main character sprite.
In my class Player.cpp
, I have some functions that calculates a deltaY/X
which decide if you are going Left/Right/Up/Down
and then you use them in the update function.
That's my code so far:
void Player::moveX(int moveDirection) {
deltaX = moveDirection * PlayerConstants::WALK_SPEED;
playAnimation(deltaX > 0 ? "WalkRight" : "WalkLeft");
facing = deltaX > 0 ? DIRECTION ::RIGHT : DIRECTION::LEFT;
}
void Player::moveY(int moveDirection) {
deltaY = moveDirection * PlayerConstants::WALK_SPEED;
playAnimation(deltaY < 0 ? "WalkUp" : "WalkDown");
facing = deltaY < 0 ? DIRECTION ::UP : DIRECTION::DOWN;
}
void Player::update(float elapsedTime) {
_x += deltaX * elapsedTime;
_y += deltaY * elapsedTime;
AnimatedSprite::update(elapsedTime);
}
Walk Speed is 0.1
right now.
Any guesses on how to move it tile by tile?
Upvotes: 1
Views: 370
Reputation: 814
Here's what you could do.
Create 2 global variables called, say, x_overflow
and y_overflow
. Now, in your update function, instead of directly adding deltaX and deltaY to _x and _y, add deltaX and deltaY to x_overflow and y_overflow. Then, add a couple if-statments checking if x_overflow and y_overflow are greater than your desired distance (i'm guessing 32px), and if they are, move your character by 32px.
Something like this
void Player::update(float elapsedTime) {
x_overflow += deltaX * elapsedTime;
y_overflow += deltaY * elapsedTime;
if (x_overflow >= 32) {
_x += 32;
x_overflow = 0;
}
else if (x_overflow <= -32) {
_x -= 32;
x_overflow = 0;
}
if (y_overflow >= 32) {
_y += 32;
y_overflow = 0;
}
else if (y_overflow <= -32) {
_y -= 32;
y_overflow = 0;
}
AnimatedSprite::update(elapsedTime);
}
I haven't really tested this code (i.e. don't copy paste), but you should understand the main idea behind it and implement it yourself. Good Luck!
Upvotes: 1