0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ What are you actually looking for? How to do tile collision? \$\endgroup\$ – Mario Dec 22 '14 at 7:58
  • \$\begingroup\$ Tile based movement. Each time it moves to the next tile rather than a pixel based movement. \$\endgroup\$ – Neil Derno Dec 22 '14 at 8:03
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Tim Holt Dec 22 '14 at 21:47
  • \$\begingroup\$ 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. \$\endgroup\$ – Aholio Dec 22 '14 at 22:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.