0
votes

I am relatively new to Pygame and trying to make a top-down racing game. Everything has currently been made and is ready to go! However, I am unable to make proper collision detection between walls and background of the "level".

What I want to happen is that the car cannot leave the boundaries of the track it is pushed back onto the track and speed is reduced. Previously this was attempted with pygame.sprite.collide_rect to no luck.

Here is a screenshot of the first track within the game and one of the cars in-game. A background will be added at a later date.

Track Screenshot

Any advice on which functions to use would be much appreciated! Would be possible to even use .collidepoint like done in menus?

Thanks, Adam.

1
any rect function works fine with rectangle objects and you have rounded track. I think: if you new in PyGame you should start with something simpler - arcanoid, tetris, sokoban - something with rectangle objects, without angles/trigonometry.furas
I would use the center of the arc and the car corners for collision detection. For instance where your car is, if any of the corners have a x > center.x and center.y + radius > corner.y > center.y - radius, and distance from center is greater then the radius of the wall, you have collision. But yeah, that may be more complicated then you want to start with.cmd

1 Answers

1
votes

What you could do is, check if the two images overlap, but one condition: the image of the track must be full opacity, and everything else transparent. Then use this code to check if overlapping.

Car_mask = pygame.mask.from_surface(CarImage)
Track_mask = pygame.mask.from_surface(TrackImage)

offset_x, offset_y = (Car.x - Track.y), (Car.y - Track.y)
if (Track_mask.overlap(Car_mask, (offset_x,offset_y)) != None):
    print("overlaps")
else:
    #Push Car Back On Track, Slow Speed Stuff
    #Cause it not touching track at all.