Pygame Car Racing Tutorial #2 - Pixel Perfect Collision

Tech With Tim · Beginner ·🛠️ AI Tools & Apps ·4y ago

Key Takeaways

This video tutorial series covers the implementation of pixel perfect collision in a Pygame car racing game, utilizing masks to check for overlapping pixels and handling collision detection, bounce behavior, and finish line logic.

Full Transcript

[Music] all right so i am back with video 2 in this series in this video we're going to be talking about collision and handling pixel perfect collision actually anyways first thing i want to do is actually make it so our car can move backwards because well we didn't do that in the last video and i meant to show that so let's do that now so to move backwards is very easy in fact it's the exact same as moving forwards except we just need to modify the velocity and everything a little bit so we're going to go and make another method here and this is going to be called move backward and inside of here we're going to say self.bell is equal to the maximum of and this is going to be self.velocity minus self.acceleration when we move backwards we need to subtract the acceleration because we're trying to go in the opposite direction so we want a negative velocity to be moving backwards because it's like the reverse gear in your car you don't turn around and go backwards you can just rotate the wheels in the other direction which is what we're going to do here and then this needs to be self.max val over 2. i don't know why i deleted that the idea of this is that we want sorry this needs to be negative is that we want the maximum possible negative velocity to be half of the velocity going forward the reverse gear in your car you cannot go up to 100 miles per hour right you can only go a certain speed there's a top speed in that so same thing here we're going to make it so when you go in reverse you're going slower than when you are going forward i don't know why that's super important but that's what we're doing so self.velocity minus self.acceleration and then negative self.max velocity over two just splitting that in half i think that's pretty self-explanatory let's now make it so we have a key that does that so we're just going to copy this and i'm just going to change this now to key this is going to be s s will go backwards and then we'll change this to be backward like that notice i have moved equals true we need that to make sure we don't reduce our speed as we are going backwards perfect now that we have that let's run the code and let's check if the reverse gear works so now i can move backwards and notice i cannot go backwards at the same speed that i can go forwards right i can go at half the speed great there you go backwards is working if you try to turn when you're going backwards you'll notice that the turning works and you actually should be turning in the inverse direction which is correct and that's why we set up all this stuff so that it just works when we add other things in the future great so what i want to do is just clean up the code a little bit here i want to take all of this stuff so keys moved all of the stuff related to moving my player and i want to make a function here and i'm going to call this move underscore player now inside of here we will just take the player card so we'll say player underscore car like that and then we could perform all of this stuff simply using player car okay so again just trying to clean this up so now inside of here i'm going to say move underscore player and i'm going to pass my player car and this will handle all the movement let me just get rid of that let's run this and let's make sure it's still working and it is we are all good okay one more small refactor i want to do is i just want to go and grab this reduce speed method here and put this inside of my car class reason being that my computer which is going to inherit from this abstract car class as well does not need to be able to reduce its speed it's going to be the same speed the whole time and so it makes sense to have this in the class where it's actually going to be used because it's not going to be used by anything else that implements the abstract car class you could leave it in there there's arguments for both but i am just going to move it here great so everything will continue to work we don't need to test that moving forward though the next thing i want to do is collision so this is where we need to talk about masks and we need to talk about how you actually handle collision of different objects in python so what i'm going to do is open up paint here we're going to start talking about masks all right so i'm inside of paint here and i'm gonna explain to you masks and how we do pixel perfect collision so let's start with traditional collision and then we can explain pixel perfect collision so let's say we have some object and let's just make it a circle for simplicity now remember i told you that every single surface in pi game is really a rectangle so even if this is all that we're showing we actually have a rectangle around this circle here so we might not see the rectangle and the reason we wouldn't see it is because all of these pixels here would be transparent pixels they wouldn't show up on the screen but they're still there it's still rectangle so let's say we have another image and let's just do it like this and maybe inside of here i don't know we have some green whatever okay this is what this image looks like point being is that these two rectangles the rectangles containing these two images are overlapping this is the overlapping area right here however if we're looking at these two images remove the rectangles they're not colliding with each other right the pixels that are present in both of the these images are not touching each other but if we were to use traditional collision which is just rectangular collision you just check if two rectangles are lying inside of each other then it would say that these two objects are colliding and this is the overlapping area but again the pixels in the images are not actually colliding so how do we fix this because i don't want it to show me that two objects are colliding unless the pixels on the screen actually look like they are colliding this is where we use something known as a mask now what a mask is is an array of values representing whether or not a pixel in an image is transparent or present whether it just exists it's not a transparent pixel now the point of a mask is that rather than performing rectangular collision like this we can simply check if pixels that are not transparent are overlapping into rectangular regions so let's clear all of this and now let's look at an example of a mask let's say we have a very simple image okay i'm going to just go with a rectangle because it's easier here and we have maybe something like this okay we have pixels all in here pixels all in here and then inside of the other two regions is transparent okay and now we have another image and let's just do something like this and maybe we only have pixels inside of this bottom left hand corner well the mask for these two images would look like this it's just going to be an array so we'd have a large array it's going to be a two-dimensional array and we would have one comma zero okay and again excuse me i'm using the mouse here and then zero comma one like that now for this image it would be similar but we're going to have nothing in the first row because we have no non-transparent pixels and then we would go here and we would have 0 comma 1 like that okay now let's imagine these masks are directly on top of each other the two objects are completely on top of each other then what we would do is we would just compare values in these arrays and see if two ones are at the same position right so we check here so okay there's no one here so we're not colliding in this region okay then we go here so okay there's no ones there so we're not colliding there we go here okay no ones we're not colliding and boom we find two ones which means we're colliding in this region right here and so we would say okay yes we are colliding because two pixels that are not transparent are touching each other there you go perfect that's all you need to know however it gets a little bit more complicated because we need to know the location of both of these masks before we can do this comparison in the example i just showed you we just imagine they were on top of each other so if i select this and i grab it it's going to be a bit rough but we imagine this mask was right on top of the other one and in that case it was really easy to check if they were colliding but what if the mask is sitting somewhere like this or sitting here or sitting up here well we need to know that and that's known as the offset so we have something and actually let's make a new file here we have something known as our calling mask and then i guess the mask that it's being called on so let's say that this here is our calling mask and then this is the mask that this mask is being called on well we need to determine the difference between the top left hand coordinates so that we can overlap these masks in the appropriate region to determine if pixels are collide so i want to calculate the displacement in x and the displacement in y so then i know the total displacement and then i can align these masks properly before i do the collision so if this is my calling mask and this is the mask that i want to find the offset on well i just need to find that i'll show you how we do that in code and then that's one of the values that we need to pass to kind of our mass collision function so that we can overlap these masks in the correct area all right that's my explanation of masks hopefully that was good enough for you now we are going to actually do this first thing we need to do though is create masks so to do this we're going to say track underscore border underscore mask now this is the whole point of having this track border is that we're going to use this border let's go to it quickly here as our mask this will be one mask and then we will compare this to the car our player car and we will see if these two masks are colliding with each other and this is actually really easy to use because its corner is zero zero right its top position is zero zero which actually just makes it way simpler for us to do the offset calculation so i'm not going to do scale image i'm going to do high game dot and this is going to be mask dot from underscore surface and we're just going to pass in here the surface we want the mask of which is our track board easy enough that's how you get a mask okay so we have that mask now what i want to do is make a method inside of my abstract car class it will go inside of abstract car because this is going to be for both the computer and my player and i will call this collide now we're going to take in self mask x equals 0 and y equals 0. with the point being we're going to pass some other mask here we'll generate a mask for our own image we'll then have the x and the y of the other mask we obviously already have the x and the y of the car we will determine if two masks are colliding in here so i'm going to start by saying car underscore mask is equal to pygame dot mask dot from underscore surface and this will be self.img so whatever image we're using for this car then we are going to calculate the offset now the offset needs to be integer values so keep that in mind so i'm just going to say int int like this and the reason we need that is because we could get some floating value when we do the subtraction we need to calculate the offset x and the offset y now the offset is relative to the calling mask in this case we're going to say i guess collision or actually go with poi which stands for point of intersection is equal to and then this will be mask dot and i believe this is called overlap of the car mask with the offset so we're going to use the other mask as the calling mask which is going to dictate how we calculate the overlap if we did the other way we need to flip the over or the not the overlap the offset sorry okay inside of int i'm going to say we're going to go with x minus self.x and y minus self.y or is the other way around let's see of course i've done it incorrectly it's going to be the other way around self.x minus x and self.y minus y okay so the reason why we're using this as our offset again is because the calling mask is the other mask that we're passing so we're going to take whatever our current x position is whatever our current y position is and we're going to subtract that from the x and the y of the other mask now that will give us the displacement between the two masks if we did this the other way around that'd be fine but we would then have to swap this and say the car mask is calling the uh the other mask okay so that's how that would work hopefully that makes a bit of sense the reason we're converting this in again is because we need integer values for the offset we cannot have floating points and our self.x and self.y can be floating point values okay so now that we have that this is going to return to us the point of intersection between these two masks if there is one now we don't actually care what that point is at least not right now we're just going to return the poi now what we can do to determine if two objects have collided is we can see if the poi is equal to none or not if there is no poi the two objects didn't collide if there was a poi then they did collide so now we have collide so i'm going to go inside of here and i'm going to check for this collision so i'm going to say if we're going to go car underscore player dot collide and we're going to do this with what mask was it this was going to be the track border mask and notice that i don't actually need to password an x and a y here because the track border is positioned at 0 0. now we actually haven't even drawn the track border but that's fine because we don't need to we don't need to draw the track border right now because we just know that it's going to be at the exact same position as where our current track is on the screen because the track border and the track are the exact same size they're pretty much the same image except one is just the border the other is not so we don't need to draw it but we can still use the mask and we know its location is going to be zero zero okay so we have that if player underscore car.collide track border we can say does not equal none there then what we can do right now is we can just print collide and that way it's really easy for us to see if we actually have collided we can just look in our console and see if well we had a clyde so let's run this and pygame.surfaceobject has no attribute overlap okay let me go here uh okay car mask pie game dot mask surface mask dot overlap ah i realized what i did here i passed the track border when i meant to pass the track border mask okay so make sure you've actually passed the mask that was the point of creating it let's run this now and okay we're all good so now watch what happens when i go into the wall notice i get a bunch of collisions and then when i get off the wall it stops for a second and if i go back to the wall it continues printing glide now you can't really see it because my whole console's filled with collide but let's quit this and clear and run again and i'll show you let's turn and let's go here and then we get a bunch of clients as soon as we hit the one okay so that is the idea behind the collision that's really all you need to know for calculating collision now that we have done that we need to do something when we hit the wall we can't let our car drive through the wall so what i'm going to implement now is a bounce so if you hit the wall you're going to bounce off the wall with the same velocity that you hit the wall with right i guess we could go into the laws of uh physics laws of physics laws of motion maybe is what it's called if you hit something with a certain velocity then you're gonna go back in that same direction right just like when you throw a ball off of a wall it comes back and you're gonna lose a bit of velocity but point being you know law of physics i want to explain more than that so inside of my player car i'm going to implement a method which is going to be bounce i'm going to say define bounce self now all i need to do inside of bounce is i just need to reverse the velocity so i'm going to say self.bell is equal to negative self.vel now this will work if we're going backwards or forwards because if we're going backwards the velocity is already negative so this will then make it positive so we go forward and if the velocity is positive then it just makes it negative right and then of course we'll just say self.move so we start moving as soon as we reverse the velocity so now all we need to do is here say self.bounce and now if we hit a wall we just bounce and sorry this is not self this is going to be player underscore car so if we hit a wall we collide we just bounce backwards and we'll go in the same well actually the complete opposite direction as the one that we hit the wall so we will continue in one second but i need to quickly thank the sponsor of this video and this series which is i'll go expert i'll go expert is the best platform to use when preparing for your software engineering coding interviews they have over 160 coding interview questions in many different categories they have heaps they have arrays they have linked lists everything that you could imagine and that you need to prepare for your software engineering interviews is available at algo expert check them out from the link in the description and use the code tech with tim for a discount on the platform okay so now that we have that let's run the code and see if this is working and let's try it out and notice that i am bouncing off the walls there you go that is what i would expect now this is a little bit glitchy i won't lie this isn't always going to work perfectly every single time and you'll notice that sometimes you will kind of hit a wall even though you don't really see a wall that's just because my image is kind of messed up a little bit the way that i had it and so you might be hitting some pixels that you can't actually really see anyways this is working good enough for me i'm i'm happy with the bounce and so we're going to move on to the next thing okay so we have now handled the collision with our walls and you'll actually notice now that you can't go outside of those bounds because well you just can't right if you hit any of the walls then you're going to bounce back inside so now we need to make it so that you can hit the finish line right so let's start drawing the finish line on the screen let's handle collision with the finish line but you'll notice that this is a little bit trickier than it seems because we have to know what direction we cross the finish line from because if the finish line is where we start right kind of starting line finish line if we just drive directly backwards we can't say that we've won the race we have to hit it from the other direction so we have to handle that okay let's go here though we have finish now let me see if i need to scale this rather than just messing around with it let's see if i did scale it in my my code previously looks like i did not scale it so that's good we can just leave it where it is but i do need to determine the position of the finish line so i'm going to say finish underscore position is equal to and i've already figured this out for you it's going to be 130 and 250. so now let's just draw this in that position and let's see what it looks like so i'm going to go to my images here and i'm going to add that as one of the images so i'm going to say finish i'm going to draw this at the finish underscore position like that so now let's run the code and let's see what we get notice the finish line is right here all right so there you go the finish line is up now this looks fine however we can see it is kind of overlapping with our track so what i'm going to do is just draw the track border over top of this so that way we get rid of any of these edges that are being cut off so this is kind of a neat solution that we can go with here what i'm going to do is just add inside of my images here and make sure you do it after the finish line by the way otherwise it won't go over top of the finish line i'm going to say track underscore border and we'll just draw this at position 0 0 not 0 m 0 0 make sure we add our last bracket there and let's run this now and parentheses does not match did i mess something up okay that looks good all right so now let's see this and notice that now the finish line is no longer overlapping the reason for that is it is actually overlapping but we're just drawing over top of it just the track border so that way everything looks good and then there you go our car is now moving around let's see if we bounce and we do sweet okay so that is good now that we have done that we want to handle colliding with the finish line so now we're going to do another thing down here we're going to say if player underscore car dot collide and now we need to get a uh sorry what is this a mask for the finish line so let's generate a mask for the finish line we'll do that from up here where is the finish line right here okay we're going to say finish underscore mask is equal to pie game dot mask dot from surface and then finish okay we now have the finish mask so now we're gonna say playercard.collide we're gonna go with finish underscore mask and then we need to pass the finish position but with an asterisk what this does is split the tuple that is storing this position so x and y into two individual coordinates and passes this to the uh the function as two arguments so if you do asterisk finished position this is the same as passing 130 and 250. okay they're identical but i figured i would show this to you because it's interesting python syntax anyways we're going to say again if that is not equal to a none then what we want to do now is just print finish okay so now let's see if we can check for collision with the finish line so i'm just going to go backwards and notice we get a bunch of finishes and then if i go up here we get finishes again so the thing is as i was saying we don't want to be able to just drive backwards and say oh yeah you finished in fact if we drive backwards we don't want to be able to go past the finish line we should only be able to go forward on the track we shouldn't be able to go backwards and cross the finish line so this is where i'm actually going to use the point of intersection to determine what direction i hit the finish line from so rather than just printing finish here i'm actually going to store this and i'm going to say finish poi collide uh yeah i guess that makes sense finish point of interest collide is equal to that and then instead of all this we'll just say finish poi collide and we will print out the finished poi collide okay so let's run this and now let's go backwards and notice that we get a bunch of zeros as we're going backwards right so if i keep going back here let's go back back back let's just go slow here notice all of these are zero zero zero zero okay and then as soon as i guess the top of my car kind of gets to the middle of the finish line here we get some actual values for the y coordinate so what we can do is we can just check if the y coordinate of the point of intersection is zero and if it's zero that means we hit it from the top so coming down if it's not that means we hit it from the bottom and we actually finished meaning we went all the way around the track so let me show you what i mean we're going to say if the finished poi collide at index 1 is equal to 0 then car.bounce so just like when we hit the wall this is actually going to be playercard.bounce we're just going to bounce meaning we're going to bounce ourselves kind of up i guess if we're going backwards trying to hit the finish line let's run this notice when i go backwards now i bounce forwards because i'm trying to cross the finish line from the wrong direction now let's go all the way around and this will take a second here but let's see if we bounce when we go from the other direction okay we got to slowly make our way through the track we can just test my driving skills here while i try to fill in the silence because there's nothing to talk about okay looks good so far maybe we need to increase the speed of this car for debugging because this this could take a long time if i leave it at the speed of four okay almost there last two bends here all right coming around and notice we only bounce when we hit the top of the finish line right like i can go on to the finish line like that it's only when i get to the top that i'm actually bouncing so that's exactly what we wanted now we can just implement what happens if we cross the finish line from the correct direction so i'm just going to put an else here because if we collided with the finish line but our y coordinate was not zero that means we actually finished so in this case we will just print finish and i'll actually implement kind of the finish behavior in the next video but for now we can add a few more methods to our cars so i'm going to go to my abstract car class here and i'm just going to define another method i'm going to call this reset now what this is going to do is reset our car position so kind of preparing for the next level right so all we'll do is we'll say self.x self.y is equal to self.start underscore position we then need to reset the angle so self.angle is equal to zero we need to say self.velocity is equal to 0 as well and then is there anything else that we need to reset i don't think so let's see rotation velocity max velocity no that looks good to me we can just do that okay so now how about we say that if we cross the finish we'll reset the car we'll set flare underscore car dot reset i'm just going to increase the speed of my car so let's make this a speed of 8 and we'll go with rotational velocity of 8 as well just so that we can turn at the same speed we can move forward and let's run this and let's see if we go any faster okay so we can indeed go faster but we do have to wait to accelerate and oh gosh that's a crazy balance okay maybe we should make the bounce a little less harsh and maybe the lower speed was was better oh my gosh okay all right all right let's uh try to get around this bend here okay yeah so i think the speed of eight maybe is is too fast uh we also could just try spawning the car right before the finish line that would probably be easier too but you guys can just watch me struggle here okay let's go and you're noticing that sometimes we're hitting like a wall that's not actually there again kind of unavoidable but as you saw there as i hit the finish line we spawned on top of the finish line we reset the car and everything was good great so with that that pretty much covers everything i need to go through in this video i'm trying to think if there's anything else i can show you but i think for now that is fine in the next video we're going to implement the computer car all right so the computer car moving around and as i said in the last video we'll do all of the kind of logic of starting the different levels moving the speed of the computer car faster you know that nice fancy text on the screen and really making the game an actual playable game anyways i hope you all enjoyed if you did make sure to leave a like subscribe the channel i will see you in another one [Music] you

Original Description

Welcome back to this tutorial series! In this video, we'll be covering collision, specifically, pixel perfect collision. But first I'll go over some things I missed in the last video. 💻 AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify interviews. Check it out and get a discount on the platform using the code "techwithtim" https://algoexpert.io/techwithtim 📄 Resources 📄 Download Image Assets: https://dev-cms.us-east-1.linodeobjects.com/imgs_3_96c03c84a7.zip Code In This Video: https://github.com/techwithtim/Pygame-Car-Racer ⭐️ Timestamps ⭐️ 00:00 | Moving The Car Backwards 04:03 | Understanding Masks 08:50 | Collision With The Track 17:20 | Adding The Finish Line 19:38 | Collision With The Finish Line 📚 Playlist: https://www.youtube.com/watch?v=L3ktUWfAMPg&list=PLzMcBGfZo4-kmY7Nh4kI9kPPnxJ5JMRPj ◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️ 💰 Courses & Merch 💰 💻 The Fundamentals of Programming w/ Python: https://tech-with-tim.teachable.com/p/the-fundamentals-of-programming-with-python 👕 Merchandise: https://teespring.com/stores/tech-with-tim-merch-shop 🔗 Social Medias 🔗 📸 Instagram: https://www.instagram.com/tech_with_tim 📱 Twitter: https://twitter.com/TechWithTimm ⭐ Discord: https://discord.gg/twt 📝 LinkedIn: https://www.linkedin.com/in/tim-ruscica-82631b179/ 🌎 Website: https://techwithtim.net 📂 GitHub: https://github.com/techwithtim 🔊 Podcast: https://anchor.fm/tech-with-tim 🎬 My YouTube Gear 🎬 🎥 Main Camera (EOS Canon 90D): https://amzn.to/3cY23y9 🎥 Secondary Camera (Panasonic Lumix G7): https://amzn.to/3fl2iEV 📹 Main Lens (EFS 24mm f/2.8): https://amzn.to/2Yuol5r 🕹 Tripod: https://amzn.to/3hpSprv 🎤 Main Microphone (Rode NT1): https://amzn.to/2HrZxXc 🎤 Secondary Microphone (Synco Wireless Lapel System): https://amzn.to/3e07Swl 🎤 Third Microphone (Rode NTG4+): https://amzn.to/3oi0v8Z ☀️ Lights: https://amzn.to/2ApeiXr ⌨ Keyboard (Daskeyboard 4Q): https://amzn.to/2YpN5vm 🖱 Mouse (Logitech
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tech With Tim · Tech With Tim · 0 of 60

← Previous Next →
1 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
39 Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

This video tutorial teaches how to implement pixel perfect collision in a Pygame car racing game, covering topics such as mask creation, offset calculation, and bounce behavior. By following the steps outlined in the video, viewers can develop their own 2D games with advanced collision detection features.

Key Takeaways
  1. Create a mask for the track border using Pygame's mask_from_surface function
  2. Calculate the offset between the car's mask and the track border's mask
  3. Determine if the two masks are colliding using Pygame's mask collision functions
  4. Implement pixel perfect collision by checking for overlap between car mask and track border mask
  5. Reverse the velocity of the car when it hits a wall to implement bounce
💡 The use of masks to check for overlapping pixels allows for more accurate collision detection, enabling the creation of more realistic and engaging 2D games.

Related Reads

Chapters (5)

| Moving The Car Backwards
4:03 | Understanding Masks
8:50 | Collision With The Track
17:20 | Adding The Finish Line
19:38 | Collision With The Finish Line
Up next
How to Connect Lovable to Supabase | Step by Step 2026
Tutorial Stack
Watch →