1

So ive been working on this project for a week or so and I haven't been able to perfect the rectangular object collision. It works well for collisions for above and below a block or even when you're towards the right of a block, but I cannot figure out how to fix the collisions when the player is to the left.

It works fine when you move against a wall, but when you travel to the left between 2 blocks share the same y coordinates, the player stops as if there is a wall in the way.

This is the code for collisions with a block to the right of the player, which works as intended:

# character to the left of the block
if p1.x + p1.width / 2 < block.x and p1.dx > 0:
    p1.dx = 0
    p1.x = block.x - p1.width

Whereas this is the code that is causing the issues:

# player is to the right of the block
elif p1.x + p1.width/2 > block.x + block.width and p1.dx < 0:
    p1.dx = 0
    p1.x = block.x + block.width

The collisions are checked using the axis alligned bounding block method, with x and y coordinates for the block being in the top left corner.

To anyone who tries to solve this, Thanks :)

1 Answers1

0

Likely you need to add additional conditions:

if p1.x + p1.width / 2 < block.x < p1.x + p1.width and p1.dx > 0:
    p1.dx = 0
    p1.x = block.x - p1.width

elif p1.x < block.x + block.width < p1.x + p1.width/2 and p1.dx < 0:
    p1.dx = 0
    p1.x = block.x + block.width

You can simplify the code a lot unsing pygame.Rect objects:

p1_rect = pygme.Rect(p1.x, p1.y, p1.width, p1.height)
block_rect = pygme.Rect(block.x, block.y, block.width, block.height)

if p1_rect.center < block_rect.left < p1_rect.right and p1.dx > 0:
    p1.dx = 0
    p1_rect.right = block_rect.left
    p1.x = p1_rect.x

elif p1_rect.left < block_rect.right < p1_rect.center and p1.dx < 0:
    p1.dx = 0
    p1_rect.left = block_rect.right
    p1.x = p1_rect.left

See also How do I detect collision in pygame?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • THANKS THIS HELPED A LOT (even if I had to make a few adjustments to it to fit my code ;) ). I would upvote it, but my rep on here is too low lmao – IronJaybo123 Oct 30 '21 at 03:28