Here is my code:
public void checkCollision() {
for (int i = 0; i < map.tiles.size(); i++) { //map.tiles is an ArrayList of the tiles on the map and size() is how many tiles are on the map, we are looping through each tile
Tile temp = map.tiles.get(i); //temp is the handle to the tile we are on (not physically on, but what tile we are on in the loop)
if (map.tiles.get(i).index != 0) { //checking if the tile is not blank, if there is actually a brick or whatever there
if (bounds.intersects(temp.bounds)) { //bounds is the rectangle that encapsulates the object. It is used for detecting intersections.
if (getX()+32>temp.x) //getX(), the x coordinate of the object, temp.x, the x coordinate of the current tile
setX(getX()-1); //push the enemy outside of the block, so he doesn't collide with it again.
if (getX()<temp.x+32)
setX(getX()+1); //same, but in opposing direction if he is going the other way
hspeed = hspeed * -1; //reverse the horizontal speed
}
}
}
}
The enemy is suffering from what I call 'rape the wall syndrome', meaning he is just bouncing back and forth, on a single brick like this when he runs into one:
[~] = enemy
[_] = brick
vertical order of frames:
[~] [_]
[~][_]
[~]_]
[~][_]
[~] [_]
[~][_]
[~]_]
[~][_]
[~] [_]
and repeat.
More about the enemy- he is a 32x32 square, and he is raised one pixel above the tiles on the ground so as not to collide with them, and have him reverse his direction in the same spot. In his 'main loop' his X coordinate is updated by his vertical speed like so:
setX(getX()+hspeed)
I don't know why he is doing this, and I don't know how to solve this. Thanks in advance to whomever can help me find the solution.