1

I'm making a Pygame program for a school project. The player character will pass through an enemy sprite without triggering the collision. How do I fix this?

CODE should be run if there is any overlap between the two sprites.

if CharY > thing_starty and CharY < thing_starty + Enemy2_height or CharY+PCHeight > thing_starty and CharY + PCHeight < thing_starty + Enemy2_height:
    if CharX > thing_startx and CharX < thing_startx + Enemy2_width or CharX + PCWidth > thing_startx and CharX + PCWidth < thing_startx + Enemy2_width:
        CODE
jofrev
  • 324
  • 3
  • 11
TheGaminja
  • 31
  • 2

1 Answers1

1

I recommend to use pygame.Rect objects and .colliderect() to check for the collision of two rectangles:

# detects collisions
charRect  = pg.Rect(CharX, CharX, PCWidth, PCHeight)
enemyRect = pg.Rect(thing_startx, thing_starty, Enemy2_width, Enemy2_height)
if charRect.colliderect(enemyRect):
    # [...]
    # CODE

If you want to do the collision detection yourself, then you've got to check if the rectangles are overlapping in both dimensions.

A range [x1, x1+w1] overlaps a range [x2, x2+w2] if the following condition is fulfilled:

intersect = x1 < x2+w2 and x2 < x1+w1

Note, w1 and w2 have to be greater than 0.

Do this for both dimensions:

if CharX < thing_startx + Enemy2_width  and thing_startx < CharX + PCWidht and \
   CharY < thing_starty + Enemy2_height and thing_starty < CharY + PCHeight
    # [...]
    # CODE
Matt Hogan-Jones
  • 2,981
  • 1
  • 29
  • 35
Rabbid76
  • 202,892
  • 27
  • 131
  • 174