Python [pygame] 12 Platforming Rectangular Collision Resolution

John Hammond · Intermediate ·🔐 Cybersecurity ·12y ago

Key Takeaways

Explains rectangular collision resolution using Pygame

Full Transcript

ladies and gentlemen boys and girls welcome back from their pie game python tutorial i'm rudely null i'll be your host this evening hope you enjoy the fine wine and the refreshments now we're going to be talking about collision resolution in the last video we were checking out collision detection and working with uh mouse movement and and using the mouse to move around and therefore determining collisions so in this video we're gonna take it to a different direction um i'm gonna be introducing collision uh resolution at least with rectangles like with these two blocks but unfortunately i'm not going to be using the mouse motion like i am before uh i'm going to try and kind of reroute or kind of tinker the program so that we'll be switching over to sort of platform movement or at least up down left and right and that sort of things so i'm gonna be using the arrow keys to control rather than the mouse and we're gonna we're gonna implement that right now the way that i'm gonna set that up is actually by introducing two new variables to our player object or not so much our player object but the block that we're controlling i'm going to set that up with h speed and we're going to be able to make control h speed and v speed for horizontal speed and vertical speed for just one instance which in this case that we've been working with it's been a block so let's set that up in the constructor that's where i'm going to set the self.h speed that's going to equal zero along with v speed that's horizontal speed and vertical speed uh i'm gonna define a function that will actually allow us to kind of manipulate that gonna pretty pretty pretty easy pretty simple i'm stuttering change speed of course we need the self keyword and we want a uh h speed and a v speed that we'll be working with all that we're doing in this function is very very simple very very easy we're just kind of adding the h speed or v speed to whatever we have this is gonna make for some pretty smooth movement if we just simply add it to what we have uh that way in case we uh change or we press multiple keys um it will be able to recognize and kind of do with it appropriately watch buttons we're pressing and when um i'm looking at my notes over here that's i think the next thing we can do is go ahead and change this functionality in the event loop that's where most of this good stuff is going to be happening we need to be able to check or at least test sorry for key presses and key left key right that sort of thing we're not going to be looking at mouse motion anymore nor are we going to be looking at mouse button down we are however going to be looking at um key types that are that are keep typed down uh this is a nested if statement so i'm actually going to create a whole new event type testing if it's key down key down and then we'll test what the keys actually are event.key you guys know how to do this um and now we'll start with our constants for left and right movements up and down in the screen we're going to be using our a block object remember we created that right up here it's being drawn on the screen every second because of our block group draw function and um we're gonna want to change the speed so if we're moving to the left the way that that works in um in the pi game window i shouldn't try to run this i don't know why i did that oh cool it actually works um to the left is this way obviously left and um pi game reach or sorry reads its grid at 0 0 x and y coordinates at the top left and uh the x coordinate and the y coordinate at the bottom right are the immense width and height of your window so in this case 640 by 480 0 0 is over here 640 and 480 is over here so it's increasing as it goes to the right increasing as it's going down which means it's decreasing going to the left and decreasing going up so that we're going to have negative numbers when we're going to the left and when we're going up and that's exactly why i wanted to uh tell you that because for the change speed function for the left key press we have to have a negative number and i'll use negative five i should probably set up a constant for what this actually is but easy enough negative five we're okay with it a player or a block should have its own speed so it can move at that speed and that way we can quickly change it without having to change multiple lines in the code but for now again this is just fine for what we need um i'm remember uh we need to pass in what the vertical speed will be in this case it's we're going to add nothing to it we're going to change nothing and then we'll go over to key right go positive now let's go up and down up remember will be negative down will be positive and that's changing the y-axis now we're actually going to change this for key up copy and paste all the code that we just wrote and it's very very simple all we're doing is changing the value of what we're adding to either negative or positive depending on what it was before n just change the size just kind of negate it just use the opposite of what you had before okay so now we actually need to be able to move the object we've added in of course for all of this handling and uh if i press the arrow keys you see nothing is going to happen i might be able to actually uh set what am i thinking i should i should set a message every time the arrow key is being pressed but that might take too long you know what i'm gonna do i'm just gonna actually print out i'm gonna print out with the uh whenever we receive an event let's print out the a blocks h speed and v speed this is a totally not important this is just a visual so that you can see that yes we are actually changing the events if i press the arrow keys oh you can't even see it because my window is too far up but you can see negative five five zero whenever i whenever i actually press the buttons okay so now that we have that set up we need to give the functionality to the player and we're going to do that in a function called update if you remember in the documentation at least for a sprite there has always been a sprite dot sprite update function and methods to control sprite behavior by default this does nothing but we're going to be able to use it whenever we want we can uh kind of implement it and make it work the way we want it to let me get back to my code and let's go write that in the uh block object okay we got the definition and um let's keep moving keep moving along here this is where we're going to want to actually change the position of the um of the player i'm going to i'm going to keep the set position function because we use that to actually put the visit put um sorry the the player or the block on the screen at runtime and i'm actually not going to put it at zero i'm not going to put it at the center of the screen anymore because it's all in that case it's already colliding with the other block i'm going to move that to zero zero just the very top of the screen and i'm going to keep the set position function like i was saying but i'm kind of going to use the same functionality by using the self set rect changing the position of it by using the rectangle properties and we're actually just going to go ahead and add on whatever the horizontal or vertical speed is in the case of movement so that's good now let's go ahead and back to our event loop down here um any any position in here should be fine i think i'll put it where i want to put it it blocked that update probably after we filled the screen of course it blocked that update now when we run this if i bring it over you can see my block in the corner i can move that with the arrow keys and now even if we move over to the block over here there is a collision because we still have our collision detection but let's actually resolve this collision so we can't go through the red block we won't be able to move past it or through it'll be like a solid object that we're literally colliding against let's add that functionality we just created the update function and that's exactly we're going to keep track of the collisions so we're actually going to be able to pass in a list of collidable objects or things that we can actually collide with let's set that up let's add a new argument called collidable and that's going to be a group a group of sprites things that we can actually collide with now in between the x and the y the change in the x and y whenever we're adding the speed we're going to want to actually set up a collision list and this is going to be a list of all the sprites that we're actually colliding with now how do we get that list well pygame is fantastic and they've got a function inside the sprite sub module called sprite collide let's check that out in the documentation sprite collide find sprites in a group that intersect another sprite okay so here are the arguments these are the sprites that we're actually looking for or at least the sprite this is the sprite that's testing whether or not it's colliding with any of the others in a specific group so in this case we want to test if this object if this block is colliding with any others so that's going to be self next we want to know the group that we're actually testing in and that's going to be collidable or the list of collidable objects that we could potentially collide with and then we continue uh do kill it says this do kill argument is a boolean value if it's set to true all sprites that collide will be removed from the group well we don't really want to remove the objects so let's go ahead and set that to false and um collided what is this collide is a callback function used to calculate it two spreads of colliding it should take two sprites as values and return a bool value indicating if they're colliding collided is not passed all sprites would have a rectifier okay okay so that's totally optional and it's not necessary for us yet when we get into circular collision and circles in the game then maybe we'll want to look at that function and see what more we can do with it um for now let's leave that as uh just the way it is so now we've got the collision list and we want to check through everything that we've collided with and see which way that we're kind of colliding up against it because if we're coming from the top we want to stop if we're coming from the right we want to stop if we want it coming from the if we're coming from the left we need to stop and that sort of thing so the way that we do this is actually going through the list for each collided object everything that we've actually hit in the collision list we want to be testing whether or not we've hit it and first we're going to do that with the x direction horizontally we set that up by testing if our speed horizontal speed is for one thing greater than zero because if it's greater than zero like i showed you guys earlier in that visual demonstration it's moving to the right because it increases as the grid goes from left to right if it's greater than zero if it's positive it's moving in the right direction so in that case we want some special values we want to be able to uh check that the self.rect the the actual position the rectangular position and and properties of this object if the right side of it remember in the in the documentation we saw that for the rect object there is some properties like x and y top left bottom and right these are the ones we're going to be using and thankfully pie game keeps track of them for us so if the self.wrecked right object is moving in the right direction then we want to set that to the left of the object that we just hit so essentially we stop moving collided object we want it's wrecked because that's going to be a sprite obviously the left side of that so the right becomes the left and they stop you can visualize this when it when the code is done and it's it's it's very visible and then we will uh go ahead and keep moving we want to test also the other direction so this is going to be an l if statement because it's the opposite but we're still testing if h speed is less than zero because if it's equal to zero we don't care it it's nothing that we should be worried about because essentially that means it's not moving but we need to be testing if it's greater than zero moving in the right direction we should actually make a comment of that and then if it's going in the left direction or if it's negative then we do the exact opposite we set the left of our object to the right of the other object all right that works just great for us now we do the exact same thing but for the vertical section the y-axis since we have already moved our position since we've actually changed the left or the right side of the object we have essentially moved and we should recheck for the collisions so we're going to want to run this collision list again then we set up the exact same oh sorry i had a collision left over here as a syntax here it's a good thing i uh good thing we noted that copy this for loop and put it again here at the bottom and now we're testing like we said earlier for the v speed in the vertical direction up and down if it's going to be positive remember that's going down if it's negative remember that's going up and rather than working with the right and the left we're going to be working with the bottom and the top going down that means that the bottom is going to have to be stuck at the top and if we're moving up that means that the top is going to be have to be going to the bottom and that's the functionality that we're building okay cool so now we've got an object that could potentially collide with things and it uses an update function with a collidable the list of collidable objects so let's uh let's see how we can finally implement this before we start our event loop we want a object that is a a group of sprites that we can actually collide with collidable objects that's going to equal pygame.sprite dot group so we want a group of these things and then we'll go ahead and add that red block that we have another block the object that we're using in our program to the list or to the group another block great so now in the code let's go back down to the update function and let's pass in the collidable objects group now i think we're ready let's run the code hopefully no bugs hopefully no errors all right we got it so i can move around and now if i move over and come in contact with it i stop i stop moving yes and i can move left and right while i'm holding down the down button but still not colliding the same thing happens with the left and the right does it happen from the bottom it does because we've got the exact same functionality so we did it we can set this block to obviously be any size we can pass that back in because we set that up in our another block block creation object we can set this to let's say be a hundred or 200 wide maybe 100 tall and that'll go in the very center because we have the offset if i bring this up we still have the same functionality with the collision and let's even put a whole other object in here let's say uh more block more block this one can be blue that can be 320 way down low let's put you down 200 uh pixels down from the center of the screen and we actually need to add that to the group so it'll be drawn on the screen let's add right at the start more block so it's essentially under everything okay now when we run the program we've got our more block down here and you guys should know here i'll make it so you can see the more block you guys should know that because this more block block is not added to collidable objects we can go right through it but the moment we add it to the collidable objects list we're not going to be able to do that so at the beginning we can set up collidable objects add more block run the program i move down and i cannot collide with this block anymore we set up a collision detection for this block awesome we did it guys we came so far thank you for watching guys i know this has been a long video i hope you understand everything that i'm talking about if you're coming from the left side if you're moving in the left direction then the left side of your object should become the right side of the other object and the same thing happens for moving up the top of your objects becomes the bottom of the other and the same functionality for all the other edges around this rectangular object that is the best part of pi game with collision detection and man we mastered it we finally got it to work okay thank you for watching guys i hope you can understand this hopefully pretty soon we'll be looking at mouse movement and how to have collisions by using the mouse to move your player but for now this this works wonderfully maybe pretty soon we'll get into gravity and start to add a little bit of a player functionality to a platforming game thanks for watching guys hope you enjoyed the tutorial i know it's been long uh if you liked the video please like the video and if you really like me and what i do subscribe that'd be uh that'd be flattering and that would help a few more videos come to the table all right see you in the next tutorial

Original Description

If you would like to support me, please like, comment & subscribe, and check me out on Patreon: https://patreon.com/johnhammond010 E-mail: johnhammond010@gmail.com PayPal: http://paypal.me/johnhammond010 GitHub: https://github.com/JohnHammond Site: http://www.johnhammond.org Twitter: https://twitter.com/_johnhammond
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from John Hammond · John Hammond · 22 of 60

1 Code Commentaries? PHP to JavaScript in Bash and PHP!
Code Commentaries? PHP to JavaScript in Bash and PHP!
John Hammond
2 Tutorials? MySQL connection with PHP and Bash!
Tutorials? MySQL connection with PHP and Bash!
John Hammond
3 Variable Naming in Python! Happy Birthday, Linux! Nokia N900!
Variable Naming in Python! Happy Birthday, Linux! Nokia N900!
John Hammond
4 JavaScript Splits The URL!
JavaScript Splits The URL!
John Hammond
5 HTML Tables in Python!
HTML Tables in Python!
John Hammond
6 HTML, Net Shares, GML!
HTML, Net Shares, GML!
John Hammond
7 Python 08 Programming Style and Comments
Python 08 Programming Style and Comments
John Hammond
8 Python 26 Object Oriented Programming
Python 26 Object Oriented Programming
John Hammond
9 75 Python Tutorials, Out Now!
75 Python Tutorials, Out Now!
John Hammond
10 Batch 14 Mathematical Expressions
Batch 14 Mathematical Expressions
John Hammond
11 Batch 85 Array Append
Batch 85 Array Append
John Hammond
12 Batch 86 Array Count
Batch 86 Array Count
John Hammond
13 Batch 87 Array Index
Batch 87 Array Index
John Hammond
14 Batch 88 Array Insert
Batch 88 Array Insert
John Hammond
15 Batch 89 Array Remove
Batch 89 Array Remove
John Hammond
16 Batch 90 Array Reverse
Batch 90 Array Reverse
John Hammond
17 Python [colorama] 00 Installing on Linux
Python [colorama] 00 Installing on Linux
John Hammond
18 Python [colorama] 09 Cursor Position
Python [colorama] 09 Cursor Position
John Hammond
19 Python [hashlib] 02 Algorithms
Python [hashlib] 02 Algorithms
John Hammond
20 Python 00 Installing IDLE on Linux
Python 00 Installing IDLE on Linux
John Hammond
21 Python [pygame] 11 Rectangular Collision Detection
Python [pygame] 11 Rectangular Collision Detection
John Hammond
Python [pygame] 12 Platforming Rectangular Collision Resolution
Python [pygame] 12 Platforming Rectangular Collision Resolution
John Hammond
23 Python [XML-RPC] 01 Research
Python [XML-RPC] 01 Research
John Hammond
24 Python [pyenchant] 03 Personal Word Lists
Python [pyenchant] 03 Personal Word Lists
John Hammond
25 FancyURLopener Authentication and User-Agent [urllib] 03
FancyURLopener Authentication and User-Agent [urllib] 03
John Hammond
26 Python 04: PEP8 Coding
Python 04: PEP8 Coding
John Hammond
27 Python Challenge! 17 COOKIES
Python Challenge! 17 COOKIES
John Hammond
28 Google CTF 2016: Ernst Echidna
Google CTF 2016: Ernst Echidna
John Hammond
29 Google CTF 2016: Spotted Quoll
Google CTF 2016: Spotted Quoll
John Hammond
30 Google CTF 2016: Can you Repo It?
Google CTF 2016: Can you Repo It?
John Hammond
31 Google CTF 2016: No Big Deal
Google CTF 2016: No Big Deal
John Hammond
32 Google CTF 2016: In Recorded Conversation
Google CTF 2016: In Recorded Conversation
John Hammond
33 Homemade CTF Challenge: 01 "Orchestra"
Homemade CTF Challenge: 01 "Orchestra"
John Hammond
34 Homemade CTF Challenge: 02 "Bae's Base"
Homemade CTF Challenge: 02 "Bae's Base"
John Hammond
35 Homemade CTF Challenge: 03 "Web Hunt"
Homemade CTF Challenge: 03 "Web Hunt"
John Hammond
36 Homemade CTF Challenge: 04 "UPX"
Homemade CTF Challenge: 04 "UPX"
John Hammond
37 Homemade CTF Challenge: 05 "The Assumption Song"
Homemade CTF Challenge: 05 "The Assumption Song"
John Hammond
38 Homemade CTF Challenge: 06 "A Brisk Stroll"
Homemade CTF Challenge: 06 "A Brisk Stroll"
John Hammond
39 Homemade CTF Challenge: 06 "I lost my password!"
Homemade CTF Challenge: 06 "I lost my password!"
John Hammond
40 web25 :: Mr. Robot : EKOPARTY CTF 2016
web25 :: Mr. Robot : EKOPARTY CTF 2016
John Hammond
41 web50 : RFC 7230 :: EKOPARTY CTF 2016
web50 : RFC 7230 :: EKOPARTY CTF 2016
John Hammond
42 misc50 : Hidden inside EKO :: EKOPARTY CTF 2016
misc50 : Hidden inside EKO :: EKOPARTY CTF 2016
John Hammond
43 Hack The Vote 2016 CTF: Sander's Fan Club [web100]
Hack The Vote 2016 CTF: Sander's Fan Club [web100]
John Hammond
44 Hack The Vote 2016 CTF Warpspeed [forensics150]
Hack The Vote 2016 CTF Warpspeed [forensics150]
John Hammond
45 Juniors CTF 2016 :: Black Suprematic Square
Juniors CTF 2016 :: Black Suprematic Square
John Hammond
46 Juniors CTF 2016 :: Six Strange Tales
Juniors CTF 2016 :: Six Strange Tales
John Hammond
47 Juniors CTF 2016 :: Lost Code
Juniors CTF 2016 :: Lost Code
John Hammond
48 Juniors CTF 2016 :: Here Goes!
Juniors CTF 2016 :: Here Goes!
John Hammond
49 Juniors CTF 2016 :: Southern Cross
Juniors CTF 2016 :: Southern Cross
John Hammond
50 Juniors CTF 2016 :: Clone Attack
Juniors CTF 2016 :: Clone Attack
John Hammond
51 Juniors CTF 2016 :: Dirty Repo
Juniors CTF 2016 :: Dirty Repo
John Hammond
52 Juniors CTF 2016 :: Hackers Blog
Juniors CTF 2016 :: Hackers Blog
John Hammond
53 Juniors CTF 2016 :: Voting!!!
Juniors CTF 2016 :: Voting!!!
John Hammond
54 Juniors CTF 2016 :: The Good, The Bad and The Junkman
Juniors CTF 2016 :: The Good, The Bad and The Junkman
John Hammond
55 Juniors CTF 2016 :: Stop Thief!
Juniors CTF 2016 :: Stop Thief!
John Hammond
56 Juniors CTF 2016 :: ROFL
Juniors CTF 2016 :: ROFL
John Hammond
57 Juniors CTF 2016 :: Restriced Area
Juniors CTF 2016 :: Restriced Area
John Hammond
58 Juniors CTF 2016 :: Oh SSH!
Juniors CTF 2016 :: Oh SSH!
John Hammond
59 HackCon CTF 2017 TRIVIA and BONUS Challenges
HackCon CTF 2017 TRIVIA and BONUS Challenges
John Hammond
60 HackCon CTF 2017 "Bacche" Challenges
HackCon CTF 2017 "Bacche" Challenges
John Hammond

Related AI Lessons

Security Belongs on the Blueprint
Integrate security into building design to mitigate physical and cyber risks
Medium · Cybersecurity
# A 4-Line HTML File Stole the Admin’s Secret — Intigriti LeakyJar CTF Writeup
Learn how a 4-line HTML file exploited a CSRF vulnerability to steal an admin's secret in the Intigriti LeakyJar CTF challenge
Medium · Cybersecurity
The Digital Gateway to Arabic Cybersecurity
Learn about the importance of language-specific cybersecurity solutions, particularly for Arabic-speaking regions, and how they can enhance digital security
Medium · Cybersecurity
Cybersecurity vs Cloud Computing – Which Career Will Dominate 2026? ☁️
Learn which IT career, cybersecurity or cloud computing, will dominate in 2026 and why it matters for your career choices
Medium · Cybersecurity
Up next
You Think Your Card Declined by Mistake? It Might Be a 2026 Scam
Tolulope Michael
Watch →