Skip to content Skip to sidebar Skip to footer

Python Rectangle Collision Handling With Pygame

I've been doing extensive research on this topic for the past few days and I can't seem to find an answer for my exact problem. So, I have a simple game set up where I have the pla

Solution 1:

Split up x/y movement.

Move x, check if colliding, if so, move back and set xspeed to 0.

Move y, check if colliding, if so, move back and set yspeed to 0.

It does mean two collisions checks per step but it's super smooth. :)

Solution 2:

The Pygame API invites you to write all your game subjects in an Object oriented way - so that your falling character will have all the "methods" and "attributes" to properly respond to things on the scenario - like hitting something.

So, if your character is defined for something as simple as:

classChar(object):# these start as class attributes, # but whenever they are assigned to with a "self.var = bla" in# a method, an instance attribute starts existing
    x, y = 0,0
    vx, vy = 0,0defupdate(self):
        self.x += self.vx
        self.y += self.vy

And your external code, upon detecting a collision, could do just this:

defmainloop():
   whileTrue:
       ...
       obj.update()
       if obj.getRect().colliderect(world[ID].getRect()): # don't do "== True" in `if's - it is just silly# take character back to the precious position
             obj.x -= obj.vx
             obj.y -= obj.vy
             # zero out velocities to make it stop:
             obj.vx = obj.vy = 0

And so on - you will soon perceive thinking of your game "things" as "objects" as they are used in programing make the code flows quite naturally - as soon as you get the way this works, look at Pygame's sprite module - which allows you to automate a lot of checks, and updates without having to explicitly write for loops for each check

Post a Comment for "Python Rectangle Collision Handling With Pygame"