Hello, I’m working on a top down 2d game and am having some problems with collision detection. Here is a basic screenshot.
https://dl.dropboxusercontent.com/u/24222531/game1.png
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 classhttp://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:
public class Player {
**SNIP SNIP**
public void tick() {
if (moving) {
updatePlayerPosition();
}
if (sprinting) {
moveSpeed = SPRINT; // 16
} else {
moveSpeed = WALK; // 8
}
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/9854530468e
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/4506e684f89
private void moveUp() { // move player up
// if not facing north, make facing north
if (!facing.equals("north")) {
facing = "north";
} else {
// else, detect collision in the direction
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?