-4

I've been trying to figure out how to detect collision in pygame I've look online for some examples and help but the ones i find don't work or i can't understand. I want a object (Car) to go to a x and y position when object (thing) collides with it here is the code can you try to make a working version or explain it

if pygame.sprite.collide_mask(car, thing):
                x = 300
                y = 250

btw this is my third attempt and it did not work.

1 Answers1

1

You need to read up more on how collisions work. Compare the xy coordinates of your car to the xy coordinates of other obstacles. Say your car is 30px wide and 20px tall. The obstacle is 30px wide and 30px tall.

then you calculate whether they are within (.5 * width) units for x or (.5 * height) units for y. You can do this by subtracting one from the other and using absolute value. If the absolute value from car.x - obstacle.x <= (carwidth * .5) + obstaclewidth * .5) then you have a collision. Do the same for Y using height of course.

I haven't done collisions in a while so that might not be 100% accurate, but that's the general idea.

emsimpson92
  • 1,779
  • 1
  • 9
  • 24