Pong: Make A Classic Game using Javascript & P5.js Framework | Saran Siri | Skillshare

Pong: Make A Classic Game using Javascript & P5.js Framework

Saran Siri, Instructor

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
12 Lessons (46m)
    • 1. Promo

      0:45
    • 2. P5.js Basics

      3:22
    • 3. Coordinate System

      1:22
    • 4. Draw The Line

      2:54
    • 5. Draw The Paddle

      4:07
    • 6. Move The Paddle

      4:36
    • 7. Ball's Collision

      8:03
    • 8. Paddle's Collision

      6:58
    • 9. Computer AI

      6:14
    • 10. Score System

      4:02
    • 11. Freeze The Ball

      1:35
    • 12. Share Your Project

      1:43

About This Class

This is my game tutorial series where I teach javascript and P5.js framework using classic games.

Check out How to make a classic Snake Game => https://skl.sh/2owxlVR

In this class, we will make a classic Pong game using free online P5.js editor

P5* editor => https://editor.p5js.org/

Transcripts

1. Promo: Hello. My name is Iran. In this class, I will show you how to make a simple, easy to follow plastic home game. Using JavaScript and P five GS framework. We will use free online data that runs on a browser. In this class, you tissue how to draw lines and players shadow Magda patio, move using keyboard, make a bouncing bow and the enemy. And finally add the score system. You can follow me for more. Came to Derosa. Now let's open the next lesson and get started. 2. P5.js Basics: in this video, we will talk about the basic functions that P five uses to set up and draw stuff. Open the browser and go to editor that p five Js dot org's in here. We have a coding panel on the left when we click, run it, restart accord here and chose the preview on the right side. I recommend signing in right away because after signing in, you can save out of projects in the cloud. Inside. According Pano, there are two main functions. Set a function and draw function instead of function. Bubi called all the ones and this is where you assign Tunisia valence to be used later. The second function below is drawl function. This is where you draw stuff and update all the logics P five. You call this function 60 times per second by default. Inside a set of function we have create can investment that setting the with and the height of the screen when creating a new project. It sets the with to 400 pixels and the high to 400 picks Those we can change the with to 600 and hit run to see the change in the preview panel and draw function Behalf background method, which repent the entire screen in the Prentice's 2 20 represents the gray color. You can change this number 2 to 55 for white color, zero for black color, go to Google and type in color picker. We can pick the color of the one for the background and use these RGB numbers instead. Copy them and put them in the Prentice's. For this game, we re use black for the background. If three numbers are the same, we can just use only the first number, even though the previous green looks clean and still is pending. The screen with black color over and over at the rate off 60 times per second below the background method. Right down print frame count in the Prentice's and hit run in the console. We can see that p five. It's printing the friend cult 60 times per second 3. Coordinate System: before we go into drawing functions. Let's take a look at the corn in their system that p five uses on over canvas p five. Who was system variable with and height than half value, We initially said by the canvas mythic. We can print them out in a draw function by writing print with comma kind in this coordinate system value of X increases when moving to the right. However, unlike in the math class, battle up, Why increases been travelling downwards? So the only gene point the point where X and Y are zero is at the top left corner. If you want to draw a shape at the center off the screen exit doll, you should be at half the size of the with why? Value should be at half the size of the height, So this dot is at X ecos with derided by two. Why equals height do right by two 4. Draw The Line: Let's draw a dash line in the middle. Two separate computers paddle and players paddle, But before drawing a line, we would have to set up its color and its size. First, to set up the color of the line re you stroke method and let's pick the white color, which is 2 55 Then, to change the size or thickness off the line, you stroke weight method. We were used one pixel for now. To draw a line, we need to identify two points on the screen. For example, if you want to draw a life on top, left corner to bottom right corner X one and why one should be zeal to x two should be the width of the screen. And why to should be the height of the screen. So be right line. Method X one is zero. Why one is zero x two is with and why to is height. But in this case, we want to draw a net for the game. X one is with divided by two. Why is zero x two is with the right by two. Same position in X direction. Why two is at the height of the screen to draw a dash line, weaken. Break this line into multiple lines with Nico caps you think Paul do? Let's comment this one and start with four. Why Eco's zero semicolon, unless then hides. Derided by 10 i plus plus inside the follow review drawl, Tiny lines line with Divided by two. Hi, it's derided by 10 times I, with divided by two I to do right by 20 plus hunch the right about 10 time Sign this Falu, who draw 10 multiple lines with equal gaps where each line is 1/20 of the height. 5. Draw The Paddle: In this video, we will draw a paddle for the player. Let's start by picking the color. Too few, the area inside a rectangle rights to you and put in the color white, which is 2 55 To draw a rectangle, we need four numbers X. Why with and height. Let's say we want a rectangle at X zero. Why 1 50 where it's with his 20 and its height is 100. The court would be wrecked. 01 50 20 and 100 so wrecked. Zero. Come on, 1 50 Coma. 20. Come on, 100. As we change its Y position, patio can move vertically. For example, we changed the Y Value to 200 now is lower than 1 50 To be able to control the panels movement better. We will store these four numbers in variables where they are easier to change. We we introduce for new variables related to the paddle, which are P x que y p w and B itch. P X is the exposition off the paddle for the P Y. Instead of using top left corner as a pivot off the rectangle, we will define P Y at the vertical center. Instead, this change will make it much easier to calculate the position. Let her own so in order to draw the same pad. Oh, at the same position. We will replace numbers with variables. Remember that P five is using top left corner as a default. Have it so X now. Eco's p X. Why? Because P y minus half off the height, which is the distance removed from the center to the top. The last two. I just patter with and pedal height. Declare these variables above the set of function. Studying with VAR for variable p x comma p y Comma Cheated for you coma pH This way it will declare multiple variables at once, then assigned these variables in the set of function. P, with stays the same at 20 p. Height is 100 p. X is at zero. The watch is now easier to imagine if you want a pad. Oh, to be at the center. P y equals half off the height in the drawer. Function removed direct method and write the new one. Richt P. Xbox People. I met us half of the paddles. Height had a with and pedal height to move the paddle to the very top. We changed the P Y 2 50 which is the half size of the pedals height, so P y. Eco's 50 to move to the bottom, change it to 3 50 6. Move The Paddle: Let's make players paddle. Move up and down using keyboard keys. President W to move up and pressing s to move down In order to move the pattern up and down between frames, we we use another variable called PV, which stands for patios. Velocity. This variable Onley affects the vertical position of the pad. Oh a both deserve function. Let's add PV in to set up this that PV 24 in drove function where methods are called 60 times per second. We can update the paddles position by adding its velocity to pee. Why? So the new p y equals D o p. Why plus p velocity you run and now it moves. Since we set TV to four, our patio is moving downwards four pixels per frame to move upwards. We can simply change. The sign of PV PV equals negative for what we want is to limit the travel Justin's so it won't go out off the screen. First we will find what the minimum off p y iss. We know that the point own talk to zero. Sochi Wash. Should be zero plus half office size, or PS, divided by two. So before drawing the pad. Oh, we will make an if condition asking if P Y is lower than pH, divided by two. So if P Y is less than he s delighted by two, then prevented from traveling further than that locked it at Ph. D. What about two U i equals it's divided by two and run do the same thing for the opposite side. Why, here at the bottom Eco's height P Y should not go further than height matters half of the Paris height. So after the first condition, we will ask if t y is greater than height minus P. H. Divided by two. It is true. Then move it back to height. Madis pH. Divided by two. Slipped aside and PV and see if it works next. Things to do is to move the pad. Oh, with keyboard keys. Review. Overwrite a function called key Pressed. Find the empty spot between functions and write down function. Key Crest Prentice's and rockets keep rest is triggered every time use it presses any tea on a keyboard, we can ask you depressed. That key is equal to S a W. So if key because Kiko's that means ICO or not, W If it is true, TV equals negative for which is the upward direction. Do the opposite thing when President s key. If key Eco's S T V equals four, which means moving downwards, just test it. 7. Ball's Collision: now that we have to paddle in this video, let's create a ball to play with. P five doesn't have a social function to draw a ball, but it has ellipse function. The big difference from drawing a rectangle is that the pivot is now at the center off. The so called This is why we changed the pivot of the rectangle a bit is easier to calculate. Really Use B X and B y for boss position B D for both diameter. A lifts method has four numbers similar to wreck method, so the full method should be ellipse. The X b, y b D and B D. A circle is just in a lips with the same with and height starting from declaring the ball variables. Ah, be X b y nbd, then assigning them instead of function this. Place it at the center of the screen. Be X Eco's with divided by two me. Why equals height you wanted By two. The diameter equals 1/20 off the height of the screen, So BD ecos height you wanted by 20 Indra function drawing ellipse. It's Bxb Why, with its beauty and height SBD, I can't run there you go the perfect circle. Next, we need to month variables to stop both velocity. We're gonna use the X for both Dallas, TX and B. Why, for both velocity Why and two more on top. The ball should have the speed limit really used. The max for the max velocity, now in a set of function, looks set to the max beat at six pixels per frame. We can adjust it afterwards, moving to the right at a maximum speed. The ex Eco's the Max and also moving downwards and a maximum speed the UAE Eco's V max in the drum function. Before drawing the ball, we will move the ball to the new position by the X and the Y, so both ellipse method the new Bo X Eco's oboe X plus V X. Same thing for why direction New y position equals O Y position plus V y. Let's run it in every frame Ball gets pushed to the right by the X and to the bottom by the why. So it moved towards the bottom right corner for both X and Y direction at the same speed. If you want to move it to the bottom left three X has to be negative. Let's try it. Put a negative sign on top. Let's make them both positive for now. The next thing is to make it bounce back when hitting the wall. When the surface of the bow touches the bottom screen, the bone should bounce back in the opposite direction. Since it hits the bottom well, the Y values should be flipped, while the velocity in X direction should be the same. Since the payment of the ball is at the center, we can check if b y, plus the radius or half of the diameter is equal to the height of the screen or not. If it's true, then flip the sign off the U Y. After updating the ball position, we will ask if you why plus radius be divided by two discredited and or equal to hunt. The reason we used greater than or equal to is that sometimes the ball is too fast and it goes beyond the height of the screen. It is true. Flip the V y by multiplying it with negative one. A new V Y equals over you. Why times negative one, then to prevent the ball from being stuck outside of the wall. Do you move it close to the edge of the wall? So you know why Eco's kind minus both ladies coalition and a top woe is also very similar. Negative the max. But we have to shake with both service. It's less than zero, so if be why minuses radius, It's less than or equal to zero. Flip the sign of ey again and also move it close to the wall, ready to bounce back. B y eco's is radius Desert out for the left wall we wish. Like if B X minus radius is negative, if it is flicked, the V X sign under the top wall condition. Start with. If be ex minister Greatest is less than zero. Then flip the sign. The ex ecos is radius. Run it finally, the right wall. If B X, which is the center plus radius, is greater than with, flip the sign and moved B x two with minus radius. Not about is bouncing between four walls 8. Paddle's Collision: after we made the ball bounce on four walls in this video, we will make it bounce on players patio, too. First we have to figure out where is the point where these two objects collide when the ball hits the paddle. Both ex minus the radius is equal to patios Exposition or P X, plus the width of the paddle. So far, we just detective collision happening on the X direction on the Y direction when it hits. But why must be between the top of the pad? Oh, and the bottom of the pad. Oh, so this is what should be inside the extent mint before the population. We will ask if B x minutes radios is less than pedals with and it's between the top and the bottom of the paddle. So if be X men SPD do what about two? It's less than or equal to p x plus PW and be wise credit and p y men s psd right about do and do you I bless them to you. Why? Plus PSD wanted by two inside we would test give it birds by printing out the work hit so print and put hit in courts says it all. First, to make it more interesting. It you're not just bombs back like a wall. The anger should be different. Best on where the ball hits the paddle window ball hits perfectly at the center. It should bounce back at zero degree angle, but even hits at the age. It should bounce back at the sharp angle. Like 75 degrees. This should make it faster and harder for the enemy to catch. To do that first, you calculate the difference between pedals y position and both y position. They will cancel out to zero when they are at the same height. Which means that off the boat is equal to center off the pad. Oh, if the bow why is nowhere, the difference will be a positive number at the top. B Y minus P. Y. We were equal to the half size off the paddles. Height yourself, so the range of this difference would be between negative half of the parasite to have of the parasite. Next, we want to simply find a range so that the top should be negative. One tomato is zero, and the bottom this one. To do that, you divide. A result by the paddles Height. She is over two, divided by PS over two is one that's part. If we multiply this formula by 75 degrees, it would give us what we want. When we hit a top, the angle will be negative. 75. Hated Somewhere here might be 30 degree and so on. We will create a variable to start the angle for that, too. We would go back to the courting panel, and we're going bringing the angle using this formula first inside. If off the Paddles Coalition, we will calculate a range in which the value is between negative one and one. So far, range equals B y menos p y grouped them and you wanted by half size off the paddles. Height pH over to. We will add another valuable to start the maximum angle and call it max angle. So far, Max and go said it to spend. If I degree in Radiant unit, which is 25 you wanted by one itty times a constant pi. Finally, the angle equals range times max angle. This angle is in red and unit. The range should be between negative 1.321 point three Let's bring it out and try to hit the ball at the edges. Using the right try and go trigonometry. We can figure out the new velocity for X and Y directions. Remove the print Mentor Update. Velocity Studying with New Re X equals the Max Times course. Sign of the angle Nuvi. Why equals the Max Times sine of the angle and hit run? 9. Computer AI: in this video, we ruin an enemy. They computers pad Oh, we will make a dumb one that tracks the position of the ball and moves towards it. The commenter should have two basic variables. As player. We have C X ey for commuter X computer. Why CV for computers? Velocity in Why direction Stunning with creating three variables. The c X See why Stevie instead of function CXT, you start at the with of the screen minus the with of the pad. Oh wishes the same s player. See why Eco's height divided by two last one CV equals zero. Then we will mimic the court of the player in draw function. Copy two players logic, including the court and updates to play US position and change the names from P to see and hit. Run copy What player does in patterns? Collision The hitting pie should be when be X plus radius goes beyond the with of the screen minus Pettus with changed. The first condition, too plus ladies is greater than or equal to with minus patios with and the rest changed. The variable names from P to see Put a negative sign on top Now to test David books are knocked. We will add to Marqise to the key pressed function just to control computers. Paddle. We can remove this later at another condition, but impressing I g equals I CV equals negative for another one for Keith Que cv Eco's for test If the Balkan bounce on the computers pad Oh, the easiest way to cash the ball is to move the pad Oh, so that the center of the paddle mashes the center off the bow. In this case, the velocity should be be Why minor? See why the result should be negative. And before updating computers position, we will calculate the difference and decided to competence. Velocity CV equals e by minus. See why get one since it detects the difference and move towards the ball right away. It is so hard for us to be to make the baht easier. We will slow down computers last e by multiplying it with another valuable called but level . This value should be less than one like 0.1, so it takes longer to reach the center off the ball. First creative arable coach, but level var but level and set it to 0.1, but level equals 0.1. Then at board level to the former. So put the parent. This is but level times the wind. MENA see why also competence paddles should not move faster than speed limit. After calculating CV, I said give CV less than negative, for it is true. Seavey, These negative four do the same thing for the opposite direction. Get one. 10. Score System: to make it Marshal Engy This video We will add a scoring system. First, we will create your variables to tracks close 14 player and one for computer bob. Play a score Peace Corps. See score able that you start at zero. Peace Corps equals zero. See score egos do. Let's put the scores at 25 and 75% of the with and at 25% off the height, go to the end of the draw function. We were used text size method to set the text ice, make it 24 point and draw the numbers using text method. So text Peace Corps, 25% times with 25% times height for computer score text. See score 25% of the with 25% of the height the players score increases with the ball hits the right wall to come be. The score increases when the ball hits the left wall. To do that, we will have to modify the Wall Coalition a bit when hitting the right wall. Key score. First course, which means increasing yourself by one when hitting the left wall, right? See score post Plus instead now window ball hits the left and the right wall. The game. Should we start by resetting on positions and velocities back? Basically go back to what we have in the set of function. We can copy the whole thing here and create a new function. Call restart, put what could be changed when playing removed. What we half in set up and just call this function instead. This way, the whole court is charter back to the collision. When hitting the wall. It should only at the point to the player and start a new game. So I generally moved this one and call restart method instead. Finally, the right wall. 11. Freeze The Ball: sometimes player may want to take a break after scoring in this video, we re freeze the ball after every score at the top. Ah, freeze in the restart Function said it to through now on the velocity of the ball in restart function should be zero. So when you run, it doesn't move in key pressed function, when players hit any key and when the freeze is true, said the velocity of the ball to what it should be. If Freeze Eco's drew the ex Eco's negatively Max, the why Eco's V. Max then changed the freeze to force when someone scores the restart from Ginny's coat and the freeze will be set back to true again. 12. Share Your Project: to share this project using this website as a host Go to file and click chair. They're full things that we can use. The 1st 1 is embedded Link. We can't embed our project in the website by adding this tack to the STM l file. We can also specify the width and height so user can see are the content and also to remove the border used frame border equals zero. The next link is a present link. This will give you full screen version of the game without the header from p five Framework . This is the one you share with your friends. The 3rd 1 is cough was green linked. Wish next new search switch back to editor mode and play around with your court. However, they cannot needed your code. It is just a copy version of it. The last one. It is a copy version of your court in the editor. More has it Things were washing