Detecting collision between two rectangles has been very simple, however making sure they don't collide for walls in a 2d game has been quite difficult. I've managed it but it's buggy and requires about 14 if statements per tick to prevent the player from passing through a wall.
if wall_bottom > entity_top and wall_top < entity_bottom: # is player between y min and max
if entity_left >= wall_right - entity.max_velocity: # is the player on the right side of the box (in or out)
if (entity_left + entity.x_velocity) < wall_right: # will the player be past the right side
if entity.x_velocity < 0: # is the player's velocity heading left (into right side)
entity.x = wall_right # x coord changed to edge of wall
entity.x_velocity = 0 # velocity reset, wall stops player
elif entity_right <= wall_left + entity.max_velocity and \
(entity_right + entity.x_velocity) > wall_left and \
entity.x_velocity > 0:
entity.x = wall_left - entity.x_length
entity.x_velocity = 0
if wall_right > entity_left and wall_left < entity_right: # is player between x min and max
if entity_top >= wall_bottom - entity.max_velocity and \
(entity_top + entity.y_velocity) < wall_bottom and \
entity.y_velocity < 0:
entity.y = wall_bottom
entity.y_velocity = 0
elif entity_bottom <= wall_top + entity.max_velocity and \
(entity_bottom + entity.y_velocity) > wall_top and \
entity.y_velocity > 0:
entity.y = wall_top - entity.y_length
entity.y_velocity = 0
I defined the edges of all the entities and check if the player will be colliding one frame into the future and then set the coordinates to the side of the box the player is on. This solution is inelegant and has had many bugs. I've been trying to come up with a better solution but can't seem to find a simple way to do it. Am I missing something obvious?