# How can I smoothly move from tile to tile?

I've looked at other games with tile based movement. I am aiming to create a game like pokemon, where the player moves smoothly to the next tile.

I am using KeyAdapter, in my KeyInput class. This basically just sets a move speed which is added to the x position of my player in the player's tick function:

if(key == KeyEvent.VK_A && ((Player)object).velY == 0){
object.setVelX(-3);
((Player)object).setDirection(Direction.LEFT);
}
//The other keys as well...


In my tick method, as I said it basically just adds it:

public void tick() {
x += velX;
y += velY;
}


And it renders in my render method through Awt Graphics. Anyways, I was wondering how I could make this have tile based movement. Each tile is 32x32 pixels. I've looked at other tutorials and they all seem to have different solutions, I'm not sure it will be compatible with what I'm using a KeyAdaptor. I assume I might have to use a modulus operator to make sure the movement is in tiles.

• What are you actually looking for? How to do tile collision? Dec 22, 2014 at 7:58
• Tile based movement. Each time it moves to the next tile rather than a pixel based movement. Dec 22, 2014 at 8:03

Use another set of variables to track where you are suppose to be, as well as where you are at.

if(key == KeyEvent.VK_A && ((Player)object).velY == 0){
object.setVelX(-3);
((Player)object).setDirection(Direction.LEFT);
currentTileX -= 32;
}


And then you could do something like this

public void tick() {
if (x != currentX && y != currentY) {
x += velX;
y += velY;
}

if ((x - currentX) < velX) {
x = currentX;
}

if ((y - currentY) < velY) {
y = currentY;
}
}


This example probably still needs some tweaking to make it just like you want, but it should get you started.

• The "< vel" test is key here in this approach. It deals with the case where your vel increment gets you very close to the target, but not quite there. That leads to crazy jumping back and forth as you keep trying to get to the point and overshooting with your increment. Dec 22, 2014 at 21:47
• Sure. I never tested the code for errors. When I wrote I thought you might have to test the absolute values to get it correct. Also, velX and velY should probably set to 0 at that point. Dec 22, 2014 at 22:14