Game Programming - Episode 81: Pixel-Perfect Collision!

The Cherno · Intermediate ·📰 AI News & Updates ·12y ago

Key Takeaways

The video demonstrates pixel-perfect collision detection in game programming using integer arithmetic and four corner collision detection, with tools like paint.net and tiles, and covers concepts like retrieval augmented generation and fine-tuning.

Full Transcript

hey what's up guys my name is a Cho and welcome to episode 81 of game programming so first things first I stepped up the audio quality hopefully um I am using a completely different audio setup this is usually the setup I use to record voice for um either music or dialogue um but I've decided to give it a shot on recording um tutorials which is kind of awkward cuz there's a lot of components here to set up in terms of Hardware but anyway hopefully the quality is worth it um because I think it's a lot better so anyway um getting back this there is there will be a bit of echo cuz this room isn't soundproof but um it's not padded but hopefully it'll be all right let me know what you think though of the um of the new stuff so we're going to talk about some pretty Advanced and Pixel Perfect Collision detection today and the reason we're going to do that is because we're going to be simulating particle physics very very soon we kind of are right now but we're actually going to step it up a notch and do bouncing off walls um in every direction obviously the problem with that is that if our Collision detection isn't absolutely perfect we're going to get a a vast array of Errors um just errors in rounding errors and everything so this really does have to be absolutely perfect and it's not right now because what we've been going for right now or so far in this series is a good aesthetical uh Collision detection which means that we want it to look nice we want it to look perfectly um look perfectly it's not a word but you know what I mean we want it to look perfect we want it to look okay okay but in reality the maths isn't actually perfect behind them so today we're actually going to pretty much do an in-depth episode um this is the kind of episode that should belong in an in-depth uh series but it is absolutely necessary that you guys realize this um and that we change some of our Collision methods around a bit so let's take a look at what we've got right now okay some of this will change hopefully for the better so what we've got right now is when this uh projectile collides here um we actually grab we get a bunch of particles exploding out of the wall um obviously I said it to explode out of the right side so if we go to the um left side you can see they don't explode left they still explode right so they go into the wall and doesn't look nice okay obviously I'm aware of that that was just to demonstrate what it would kind of look like once we added some kind of bouncing here now they aren't bouncing right now okay all we're doing is we're setting um we're basically saying that if for some reason this XA variable which is the uh the X direction of where we want to um animate our next frame to um if that uh if that direction is uh negative let's make it positive that's what we're saying right now so in other words they cannot possibly go left these particles um because we're overriding that now that's a very that's a pretty bad way of doing that and the reason it's bad um first and foremost is because it's it's situational right there's only this this only works in one situation and we could do a bunch of if St being like okay well if we hit the wall from the right side but the thing is if we if we do that we're going to get a seriously a lot of problems because look at these walls there is no way that we can handle all of these PR precise Corners here that's going to be a nightmare to handle which is why we actually need to implement some kind of physics here um so the first problem that we have is probably stems in um our wizard projectile class which is actually open already um now I'm not going to touch the players Collision okay that's irrelevant absolutely irrelevant right now um players Collision to walls is only there for aesthetical reasons okay there is absolutely no simulation that needs to go on when to play cizer with the wall the only reason that this wall Collision actually exists is because we want to stop players from getting out of the level or going you know getting out of corridors whatever we just want to stop him we're not simulating anything and because we're not simulating anything there's no need to improve that Collision okay that's I'm putting it blunt okay there's actually no need to improve that Collision it works fine as as it is right now now feel free to improve it for yourself if you want but this is usually here for aesthetical RS now sorry I just hit the hit the microphone cable now um for our particle collision though or let's just start with our projectile Collision that needs to be absolutely perfect now why does it need to be perfect okay why the reason is we add a particle spawner at that location at the location of where we actually Collide now the problem obviously is that if we collide and we you know are already inside the wall just a fraction we're going to get an error because well we're not actually going to get an error but what's going to happen is all those particles are going to spawn already inside the wall and they're not going to be able to get out of the wall cuz they're already in there um and really we just want to fix that up a bit so I'm going to uh control click on this tile Collision if you're not using Eclipse then I don't know how you do that but I'm just going to go to level class um and in the level class we we do have a method that we made called tile Collision now all of this is quite situation with this time 2 - 12 stuff we want to kind of make this a universal a universal method that we can use to make any entity collide with a tile or rather check for a collision uh in a tile and the way that we're going to do that is we're going to change around a lot of these parameters now let's just take a look at what we need first okay what do we need to collide an entity with a um a tile we need uh preferably it's um well essentially what we need right is it's X and Y our location where it's going and um the size of it which is what we seem to be declaring here that's roughly what we need okay this XA and ya they never used separately if you notice here we only ever use them in use them together we just add them together so in other words what that tells me right now is that that can be done outside of this so what we really need is we need an x coordinate we need a y-coordinate and we need a size the there's actually one more thing we need that I'm not going to cover right now but that's what we need that's all we need okay so these two if you just don't know that already these two can both be accessed through through through an entity okay so if we just open our entity class and I'm literally talking about our entity class you can see we've got an integer here for X and Y now we've got a double here for x and y and that's not that doesn't really matter um yeah seem to be overriding and we do have doubles here but um that's okay that's fine that'll still work um in fact we probably don't exactly need to keep them as doubles um when they get fed in uh but because of the fact that sometimes we do have doubles I'm not going to probably use an entity I am just going to um make uh you you feed in numbers so what I'm going to do is I'm still going to make sure that this is an integer okay um but I'm only going to make X and Y I'm not going to make x a and ya a um so we got x y and a size okay that is a very very Universal method okay that can be used for anything um now let's clean this code up a bit we don't need this anymore all we need is X and for here all we need is y okay pretty simple uh I think we got an extra bracket somewhere cuz it's complaining maybe here yep great okay so at the moment looking a lot cleaner um let's go back to wizard projectile and fix this little error here I'm going to change X to be n to be X Plus NX and I'm going to change y to be y + NY which is of course our uh translation Vector um and I need to cast them as an integer so I'm going to cast them as an integer after they've been added together that's probably going to be more precise if not we can change it at any time of course um so I'm going to add them together then cast them to an integer and that'll give me pretty much the pixel to which they want to advance to these these projectiles of ours um now back in the level um this thing is is quite random here and um as in these numbers okay they're not actually they're just again aesthetical we're kind of playing around with those numbers until we get something that looks okay now we're going to do it mathematically now um uh I'm not going to draw you a diagram because we're going to be here for half an hour if I do cuz this is quite complex if you want to see this again I'm raising my voice so you guys can hear hear me all you are already dozing off um if you want to see me explain this properly and actually draw you diagrams who you absolutely understand this let me know I'll make a separate video that's not part of this series that will cover this four corner Collision detection in like about 30 minutes so that you get everything about it um but all you need to know right now is that these are the four corners of a tile a tile is square okay anything that's rectangled is four corner Collision detection works for in fact it's probably the thir method um especially if there's no serious physics involved and by serious physics I mean like uh you know squares gliding with circles or whatever um and actually working out vectors to to do with that but um what we need to do right now is we need we need to calculate these four corners now the way that we do this roughly is when if we take COD 2 since C is less than four that's how many times we do it we do it we actually Loop through the for Loop four times right so for each time we Loop is either 0 1 2 or 3 right because if it's less than four we get out of the loop so if it's greater than four we get out of the loop if it's greater than or equal to four we get out of the loop because if it's less than four we continue the loop um so in other words um we get the values of c being 0 1 2 and 3 now if the values of c are either 0 or two this will equal zero okay because we're moding it by two now if C is 1 1 mod 2 is actually equal to 1 and so is 3 mod so what happens is if this is equal to0 which is in the case when C is 0 and two I'm trying to explain this briefly by the way um then we get zero here and obviously Z multiplied by size is zero okay um and because of that we get zero for here and and for here so all we're really doing is subtracting 12 from X now for the other ones this is equal to one one mod sorry this is equal to 1 so we just get 1 * size so what we're doing effectively by doing this is we're just is having a way to either use this size or not so we're we're making ourselves a way to either add this size to the x or not and by doing this we're enabling us to check the other Corner the corner that's further away from the origin um and that's roughly how it works okay so in order to fix this we first of all need to change this to a subtraction and all we need here is just the size let's get rid of this okay that's the most basic form of this all we're doing is if we're we're currently in the full loop at the appropriate Corner we're just going to subtract the size of this rectangle or in other words well for this the width for this the height but because it's a tile collision and tiles are square we don't need a separate width and height variables since they are equal to each other so and Y of course does the same thing but for y um now this is pretty basic I am going to change this uh just a quick optimization here um I'm going to change this divided by 16 to uh right shipped by 4 that's the same thing does exactly the same thing because 2^ 4 is equal to 16 okay this is a quick optimization most compiled probably do it for you but it's probably um I actually find this more readable to be honest um but anyway the point is that um we've got this nice equation here now this is going to be Pixel Perfect okay as long as the size is the size of the object we're checking against now this is where the interesting stuff comes in if I open our folder here let me just find it um if I open our game programming and we go to rain and here we are in resources we have textures of course and we have our sheets and we have projectiles let's open up wizard. project uh PNG and we'll open it with uh paint.net so if we open this what we see here is um that this is drawn in the center okay obviously we'd be checking in the top left corner that's obviously the origin um this is in the center though that's a bit of a problem it's not really but it is a bit of a problem because Collision won't occur here Collision will occur here now we need to offset it because of that so we need to offset it 5 pixels to the right and 4 pixels downwards so we just need to remember that so what we need here because of that is an X offset and a y offset and what we're going to do is we're going to subtract this x offset here and we're going to subtract the Y offset in the Y okay and this is pretty much going to give us a really really precise Collision detection method um if we go back to wizard projectile we'll have to add these values now the size is seven um I'm kind of regretting that I Clos paint on itet but if I open it right now and we'll just open um the recent stuff that we're doing which is uh wizard yep um if we if we take a look look at that our size is uh as you can see seven so our width is seven pixels and our height is 7even pixels that's why I'm using size seven okay um but what we also need to add right now is the offset so five and four okay um very very simple and let's take a look at what that looks like right now so you can see that um It's Made pretty much no difference here but what you should be able to see is um I think we may have offset it the wrong way though so let's make make sure that um we do keep the offset uh correct yeah there we go okay so it looks like it has to be plus um but yeah so what we're doing here is we're keeping the Collision uh ridiculously precise here you can see that um it's not making much of a difference because again we did match it aesthetically but right now it's actually hitting the tile and that's what's kind of causing it to uh stop um so with that in mind that is that is the Collision method that we're going to use Okay so again all you need to remember is you want to subtract C mod 2 times the size of your Collision that you wanted um detect and then you want to add an offset to it if if required okay and that's for the X um finally you obviously want to divide it by the um size of your tile so that you get it in uh tile precision and you can actually get the relevant tile here and check if it's solid but um the same thing happens for um y except with divid two of course and using the Y variable instead of X um but that is going to give us the basis of the Collision that we're actually going to use for our particles um and in fact what we're going to do we're actually going to write our own Collision um method here we're not going to um actually use this one because we need more parameters than this we actually need specific parameters such as the direction since we do want to um create physics but that is going to be the basis for um precise Collision detection uh for our game okay so again if you want me to demonstrate this maybe without a tile uh thing maybe write a quick game and just demonstrate this cont this concept with two rectangles and draw you diagrams all that stuff for an in-depth episode let me know I'll gladly make that um and because this is something that Collision detection is something that people do not understand very well and it's something that you really should understand very well okay so that is wrapping up episode 81 of game programming one thing I want to mention guys is that um I am quite I'm actually quite busy right now in my life um and because of that making these game programming episodes something I really want to do but it's something I find hard to do at times so I'm going to cut you guys a deal okay for every 100 likes that a video gets and by video I mean game programming video so this one for example for every 100 likes that this video gets I'm going to release an extra video of game programming so in other words if it's a Saturday and I wasn't planning to release an episode today I will release one today okay that's how it's going to work so every 100 likes so if there are 200 likes on this video I'm going to release two episodes 300 likes three episodes th000 likes 10 episodes okay not even kidding so that's going to be the deal that I'm cutting with you guys because likes first of all motivate me to do this honestly if I see people liking my content I'm like dude I want to make more and second of all because likes actually help my channel grow which is something that is obviously a good thing so um that is episode 81 of game programming if you did hit that like button and I will make many more episodes to come and let me know if you want that indepth the in-depth uh series or at least for this episode for Collision um but other than that guys thanks for watching seriously and I'll see you guys next time goodbye [Music]

Original Description

Follow me on Twitter to stay updated! http://www.twitter.com/thecherno ------------------------------------------------------------------------------------------------- In this video: - How to use four corners to detect rectangular collision - How to implement 2D collision detection ------------------------------------------------------------------------------------------------- Website: http://www.thecherno.com Twitter: http://www.twitter.com/thecherno Facebook: http://www.facebook.com/thecherno Subreddit: http://www.reddit.com/r/thecherno/ Steam Group: http://www.steamcommunity.com/groups/thecherno ------------------------------------------------------------------------------------------------- Outro music is by Approaching Nirvana: http://www.youtube.com/approachingnirvana
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from The Cherno · The Cherno · 0 of 60

← Previous Next →
1 3D Game Programming - Episode 1 - Window
3D Game Programming - Episode 1 - Window
The Cherno
2 3D Game Programming - Episode 2 - Game Loop
3D Game Programming - Episode 2 - Game Loop
The Cherno
3 3D Game Programming - Episode 3 - Arrays
3D Game Programming - Episode 3 - Arrays
The Cherno
4 3D Game Programming - Episode 4 - Drawing Pixels!
3D Game Programming - Episode 4 - Drawing Pixels!
The Cherno
5 3D Game Programming - Episode 4.5 - How Rendering Works
3D Game Programming - Episode 4.5 - How Rendering Works
The Cherno
6 3D Game Programming - Episode 5 - Playing with Pixels!
3D Game Programming - Episode 5 - Playing with Pixels!
The Cherno
7 3D Game Programming - Episode 6 - Performance Boosting
3D Game Programming - Episode 6 - Performance Boosting
The Cherno
8 3D Game Programming - Episode 7 - FPS Counter
3D Game Programming - Episode 7 - FPS Counter
The Cherno
9 3D Game Programming - Episode 8 - Alpha Support and More
3D Game Programming - Episode 8 - Alpha Support and More
The Cherno
10 3D Game Programming - Episode 9 - Beginning 3D
3D Game Programming - Episode 9 - Beginning 3D
The Cherno
11 3D Game Programming - Episode 10 - Floors and Animation
3D Game Programming - Episode 10 - Floors and Animation
The Cherno
12 3D Game Programming - Episode 11 - Rotation
3D Game Programming - Episode 11 - Rotation
The Cherno
13 3D Game Programming - Episode 12 - User Input
3D Game Programming - Episode 12 - User Input
The Cherno
14 3D Game Programming - Episode 13 - Render Distance Limiter!
3D Game Programming - Episode 13 - Render Distance Limiter!
The Cherno
15 3D Game Programming - Episode 14 - Basic Mouse Movement
3D Game Programming - Episode 14 - Basic Mouse Movement
The Cherno
16 3D Game Programming - Episode 15 - Textures + More!
3D Game Programming - Episode 15 - Textures + More!
The Cherno
17 3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
The Cherno
18 3D Game Programming - Episode 16.5 - Exporting Runnable Jars
3D Game Programming - Episode 16.5 - Exporting Runnable Jars
The Cherno
19 3D Game Programming - Episode 17 - Small Adjustments + Birthday!
3D Game Programming - Episode 17 - Small Adjustments + Birthday!
The Cherno
20 3D Game Programming - Episode 17.5 - Creating an Applet
3D Game Programming - Episode 17.5 - Creating an Applet
The Cherno
21 3D Game Programming - Episode 18 - The Beginning of Walls
3D Game Programming - Episode 18 - The Beginning of Walls
The Cherno
22 3D Game Programming - Episode 18.1 - A Few More Things
3D Game Programming - Episode 18.1 - A Few More Things
The Cherno
23 Episode 18.5 - Creating an EXE File in Java
Episode 18.5 - Creating an EXE File in Java
The Cherno
24 3D Game Programming - Episode 19 - Rendering Walls
3D Game Programming - Episode 19 - Rendering Walls
The Cherno
25 3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
The Cherno
26 3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
The Cherno
27 3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
The Cherno
28 3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
The Cherno
29 3D Game Programming - Episode 24 - Making Our Launcher Work
3D Game Programming - Episode 24 - Making Our Launcher Work
The Cherno
30 3D Game Programming - Episode 25 - Writing and Reading Files
3D Game Programming - Episode 25 - Writing and Reading Files
The Cherno
31 3D Game Programming - Episode 26 - Custom Resolutions
3D Game Programming - Episode 26 - Custom Resolutions
The Cherno
32 3D Game Programming - Episode 27 - Decorating the Launcher
3D Game Programming - Episode 27 - Decorating the Launcher
The Cherno
33 3D Game Programming - Episode 28 - Continuing our Custom Launcher!
3D Game Programming - Episode 28 - Continuing our Custom Launcher!
The Cherno
34 3D Game Programming - Episode 29 - Launching The Game
3D Game Programming - Episode 29 - Launching The Game
The Cherno
35 3D Game Programming - Episode 30 - Colour Processing In-Depth
3D Game Programming - Episode 30 - Colour Processing In-Depth
The Cherno
36 3D Game Programming - Episode 31 - Sprites!
3D Game Programming - Episode 31 - Sprites!
The Cherno
37 3D Game Programming - Episode 32 - Sprite Mapping
3D Game Programming - Episode 32 - Sprite Mapping
The Cherno
38 3D Game Programming - Episode 33 - High Resolution Rendering
3D Game Programming - Episode 33 - High Resolution Rendering
The Cherno
39 3D Game Programming - Episode 34 - Entities
3D Game Programming - Episode 34 - Entities
The Cherno
40 Genesis - My Game for Ludum Dare 24
Genesis - My Game for Ludum Dare 24
The Cherno
41 Vlog + Ludum Dare Results
Vlog + Ludum Dare Results
The Cherno
42 Game Programming - Episode 1 - Resolution
Game Programming - Episode 1 - Resolution
The Cherno
43 Game Programming - Episode 2 - Threads
Game Programming - Episode 2 - Threads
The Cherno
44 Game Programming - Episode 3 - Game Loop
Game Programming - Episode 3 - Game Loop
The Cherno
45 Game Programming - Episode 4 - Window
Game Programming - Episode 4 - Window
The Cherno
46 Episode 5 - Buffer Strategy
Episode 5 - Buffer Strategy
The Cherno
47 Game Programming - Episode 6 - Graphics Initialized
Game Programming - Episode 6 - Graphics Initialized
The Cherno
48 Game Programming - Episode 7 - Buffered Image and Rasters
Game Programming - Episode 7 - Buffered Image and Rasters
The Cherno
49 Game Programming - Episode 8 - The Screen Class
Game Programming - Episode 8 - The Screen Class
The Cherno
50 Game Programming - Episode 9 - Rendering Pixels
Game Programming - Episode 9 - Rendering Pixels
The Cherno
51 Game Programming - Episode 10 - Clearing the Screen
Game Programming - Episode 10 - Clearing the Screen
The Cherno
52 Game Programming - Episode 11 - "Out of Bounds, Baby!"
Game Programming - Episode 11 - "Out of Bounds, Baby!"
The Cherno
53 Game Programming - Episode 12 - Negative Bounds
Game Programming - Episode 12 - Negative Bounds
The Cherno
54 Game Programming - Episode 13 - Timer
Game Programming - Episode 13 - Timer
The Cherno
55 Game Programming - Episode 14 - FPS Counter
Game Programming - Episode 14 - FPS Counter
The Cherno
56 Episode 15 - Tiles
Episode 15 - Tiles
The Cherno
57 Game Programming - Episode 16 - The Map
Game Programming - Episode 16 - The Map
The Cherno
58 The Walls 2 - Minecraft PvP Survival Map
The Walls 2 - Minecraft PvP Survival Map
The Cherno
59 Game Programming - Episode 17 - Key Input
Game Programming - Episode 17 - Key Input
The Cherno
60 Game Programming - Episode 18 - Controlling The Map
Game Programming - Episode 18 - Controlling The Map
The Cherno

This video teaches pixel-perfect collision detection in game programming, covering integer arithmetic and four corner collision detection, and is relevant for game developers and programmers. The lesson covers the importance of precise collision detection and provides steps to implement it. By following this lesson, viewers can improve their game programming skills and create more realistic gameplay.

Key Takeaways
  1. Change Collision methods around a bit
  2. Implement physics to handle precise corners and edges
  3. Control click on tile collision
  4. Open level class
  5. Change parameters in tile collision method
  6. Access X and Y coordinates through entity class
  7. Clean up code
  8. Calculate four corners of a tile using modulo operation
  9. Subtract size from X to calculate corner positions
  10. Subtract size from x
💡 Using integer arithmetic and four corner collision detection can provide precise collision detection in game programming, which is essential for realistic gameplay and simulating particle physics.

Related Reads

📰
Musk thanks Micron for chips, and builds a $55bn fab to replace it
Elon Musk thanks Micron for providing Tesla with a significant allocation of memory chips, highlighting the scarcity of this crucial component in the AI boom
The Next Web AI
📰
Jensen Huang calls the AI jobs panic ‘complete nonsense’, and takes aim at his peers
Nvidia CEO Jensen Huang dismisses AI job replacement panic as 'complete nonsense', offering a contrasting view to his peers
The Next Web AI
📰
IMF says Africa has to keep lights on before it can bet on AI
Africa's AI ambitions are hindered by unreliable electricity, highlighting the need for basic infrastructure before investing in AI
TechCabal
📰
What Does Job Security Even Look Like In 2026? It Starts With Skills
Job security in 2026 requires adapting to AI and economic uncertainty by acquiring in-demand skills
Forbes Innovation
Up next
The Actual Metric to Track With AI | @SCALER
SCALER
Watch →