Hello, I'm working on a top down 2d game and am having some problems with collision detection. Here is a basic screenshot.

My issue involves buggy movement. If I spam movement keys near a wall, I can pass through and get stuck. I think my problem may be related to multiple threads, but I am not sure.
I have a text file grid of integers read in for collision, 1 = not passable, 0 = passable. My checkCollision function checks the proposed new player position for a collision, and disallows that movement if there is a tile.
I use a overridden Keymanager class
http://pastebin.java-gaming.org/b9854254086 to alter Player's public variables UP, DOWN, LEFT, RIGHT to transfer keyboard to game logic.
Here is the player tick class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class Player { **SNIP SNIP** public void tick() { if (moving) { updatePlayerPosition(); }
if (sprinting) { moveSpeed = SPRINT; } else { moveSpeed = WALK; }
if (!moving) { if (up) { moveUp(); } if (down) { moveDown(); } if (right) { moveRight(); } if (left) { moveLeft(); }
} |
Here I update the player movement if they are still in the process of moving from one tile to another.
http://pastebin.java-gaming.org/9854530468e1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| private void updatePlayerPosition() { switch (facing) { case "north": if (!detectCollision(tileX, tileY - 1)) { northAnimator.update(System.currentTimeMillis()); y -= moveSpeed; if (y % 32 == 0) { moving = false; tileY = (int) pixelsToTileY(y); } } break; case "south": *SNIPSNIP* } } |
This simply changes facing direction, sets moving to true, and lets the above method handle the rest.
http://pastebin.java-gaming.org/4506e684f891 2 3 4 5 6 7 8 9 10 11 12 13
| private void moveUp() {
if (!facing.equals("north")) { facing = "north"; } else {
if (!detectCollision(tileX, tileY - 1)) { moving = true; } } } |
Somewhere in here there is a bug going on. I know the detectcollision method is working properly as I debugged it with println's. It seems that sometimes, while I am actively "Moving", my direction can change and place me in a wall. Note that this code has double collision checking, I tried with one and it simply let me into impassable walls, with two checks i actually get stuck in the wall and cant move at all.
Can anyone help me out here. Is there a simpler way of getting animated tile movement?