I have a game where the bullet is moving so fast that in a single frame it is already across the screen. That being said, it has already collided with multiple walls. Currently, I have a rectangular image that spans from where the bullet currently is, to where the bullet will be in the next frame, in order to not miss any zombies that may be in between.
I also kill the bullet if it collided with any wall, before checking if it collided with any of the zombies because what happened was that if there was a zombie behind the wall and I checked for the zombie collisions first, it would kill the zombie and then kill the bullet.
So basically, I would like to know a way to find the coordinates of where the bullet collided with the wall so that instead of advancing the bullet at its full speed, I will just advance it to just before where the collision is, check for zombie collisions, and then kill the bullet.
I am using mask collision.
Unfortunately
PyGame
doesn't give us a built-in means of returning collision points easy way of doing this so there is a bit of leg work to do.However, before I explain that, you mentioned in your question that the bullet is moving very fast. I'm not sure how fast we are talking so this might not apply, but in my experience collision becomes a hit and miss at high speeds, especially if you're working on a slower computer.
Assuming that
^
isn't applicable:We can use pygame.Rect.colliderect to trigger an if statement.
Simply swap out and for the actual rects and you should be good to go. One thing to note is that if the bullet is moving right to left, you will have to add the bullet's width to the x value, and if the bullet is moving top to bottom, you will have to add the bullet's height to the y value.
Note: Remember to add
pygame.Rect(<bullet-rect>)
andpygame.Rect(<wall-rect>)
to each value or you'll get an error.If the bullets travel too fast to collide with the walls or enemies, you need ray casting (or alternatively move the bullets in multiple small steps). Here's a simple ray casting example that returns the closest collision point. I use vectors and
pygame.Rect.collidepoint
to see if a point along theheading
vector collides with an obstacle.