Code a Platformer Game | 3. Hitboxes & Animation

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello fellow scratchers i'm grif patch and this is part three of our classic scratch platformer tutorial today we are going to learn about player animation and hitboxes have you heard of the term hitboxes before up until now our player has been a square today we are switching to using a cat-shaped costume sprite collisions suddenly become more problematic this is where hitboxes come in super useful solving many of our collision woes stay tuned to learn why this is a fun episode that will transform the look and feel of our game and the animation will really bring things to life we'll begin where we left off in episode 2. make sure to save the project as a copy from the file menu this is now episode three okay guys let's get scratching to teach about player animation and hitboxes we are going to be switching to using the scratch cat costumes these were included in the original resource project that many of you will have remixed from episode 1. if you want to use your own costumes that's no problem at all but you will have to adapt the tutorial a little to make it work but i hope it'll be clear enough where so scroll down to costume28 it's named stand here is scratch cat in his idle standing pose it's worth noting especially if you want to use your own costumes in the platformer how a costume is positioned on the editing canvas this is really important and shouldn't be overlooked this is the center of the costume canvas and when you place or draw a player costume you want this point to be the middle of the player costume 2. the reason that this is important is that as a sprite is rotated or flipped left and right in your game this is the position they are rotated and flipped around an off-center costume leads to an off-center movement like this a correctly centered one looks much more professional right good don't forget scratch provides a helpful way to make things centered as you move a shape around it will snap to the center of the canvas as you draw close enough to it this allows you to keep things all nicely lined up okay lesson over with our standing sprite selected i'm going to run the project wowzers that is one large scratch cat this level was really designed for a much smaller player but anyway it's kind of fun since we will be able to check out his animations easier this way so to compensate for his size open the code tab and we'll set the jump force to say 17 or 18. running that again right now i can reach the first platform in a single leap so things seem to be working okay what's all the fuss about needing hitboxes then ah look at this if i edge off this platform my face catches on the side and i'm able to continue walking even on my whiskers that's rather unnatural right i can even still jump yeah these whiskers can be useful climbing tools apparently it's surprising that they are so robust so why didn't we see this happening with our cute guy character the answer is quite straightforward they were a perfect square with no sticking out features that could get caught on the level luckily for us with a little work we can have the best of both worlds we just need to use you guessed it hit boxes to demonstrate this click back into the costume editor and find costume 28. here it is so to create a hitbox costume of my own start by duplicating costume 28 then select the entire costume on the canvas we can then group the whole costume together using the group button this will make our lives easier as we draw the hitbox next with the rectangle tool draw a bounding rectangle around scratch cat it should only just cover them don't make it too big now important thing is that there are no parts of the cat sticking out past the rectangle excellent let's run the project this is really quite funny to see it's scratch cat like you've never seen him before the scratch cat in a box platformer hey but here's the thing did you notice that the box around our player is actually stopping us getting trapped on the edge of platforms this is good news okay then so if you are still following along then i just need to report that this large sprite will get stuck trying to move on to scene 2. this is because the level wasn't designed for such a big character we'll not worry about that now but it does make me realize that it's not so easy for you watching this video to see when my player does get stuck for all you know i may just not be pressing any keys so how about i make the background change to bright red when we get stuck oh before we do any coding ensure we name this costume big hitbox okay sweet come into the code and find the when i receive tick player script we should simply never be touching the ground at the start of a tick player so if we are touching level then we are stuck to switch the backdrop color we can simply switch back drop two and this is the clever bit the touching level block wow that's weird isn't it this will change the backdrop costume to a costume named true or false true if we're touching the level and false if we are not okay we can work with that click into the stage backdrop and make sure we have two free backdrop costumes i'm creating a new second one name the first one false and the second one true so remembering that we change the backdrop to true if we are touching the level we therefore want this costume to be bright red nice did you know that red was my favorite color we'll leave the false costume blank and give things a test by staying in the project view we can just drag scratch cat and drop them overlapping the level boom look at all that redness we must be colliding good job i can also test it by walking off the right yeah now it's clear we are stuck i can now use this to better explain why even when using hitbox costumes we can still have issues with sprite collisions for this we need to talk about sprite rotation and sprite rotation styles our guy sprite was designed for simplicity and he only ever faced one direction scratch cat on the other hand wants to face in the direction they are moving in and herein lies our problem let me demonstrate click into the player's direction box here up pops the direction dialog do you see these three icons across the bottom using these we can choose between three possible rotation styles for each sprite click on the first one this is the all-around rotation style and is the default for all new sprites in this style i can rotate the sprite freely this is really great for say a space shooter or any top-down style game but not so great for a platformer it does highlight though that rotation must be considered when thinking of collisions you see how changing the direction is causing the sprite to collide with the level even though its position is not changed okay so next up we have the left right rotation style the middle option this is the style used by the default scratch cat where changing the sprite direction no longer causes them to rotate but instead they turn to face the left or right well that's cool behaving as you would expect in a platformer game also look no bright red backdrop as we turn so this mode seems better suited to hitboxes as the costume is not coming into contact with the level as the costume is flipped left or right but there is still potential for problems if i walk flush up against the wall to the left and then change direction did you see we appeared to move further away from the wall okay then walk up closer and turn around again boom again we are stuck in the wall yes even tiny differences caused by flipping the hitbox can cause our sprite to get stuck this is possibly one of the most common bugs that i've seen in scratch's platforming games luckily there is a simple solution the final rotation style is the do not rotate style as the name suggests with this enabled the sprite doesn't follow the direction value at all i can wiggle it all i like and the sprite doesn't budge an inch fantastic for ensuring our hitbox works glitch-free right then so we know what rotation style we are going to use for collisions so let's try to put this together in the game begin by finding the when i receive game loop introduce a broadcast before all the others with a new message of tick first this will be the first thing to run before the others platforming scripts so it is a good place to switch to the hitbox costume so add a when i receive tick first tap lock and switch the costume to big hitbox then from the motion category scroll down and find the elusive set rotation style block not a commonly used block but it allows us to switch rotation style to don't rotate right here in our code very useful next we want to ensure we switch back to the real cat costume after the player's finished moving this game tick the best place for that will be at the end of the when i receive tick player script however it will serve us well to make a new custom block to accomplish this name it set costume and run without screen refresh do pop the set costumes block at the bottom of the tick player script ready to run after all the movement and collisions are done so back in the set costume script for now we'll keep this simple we use the set rotation style block again returning us to the left right style then switch costume to stand cool later on we'll come back and add support for player animations but for now run the project brilliant do you notice the difference yep the hitbox has gone we're only seeing the cat now yay we can move around and if i rotate my cat we see the left right style is working but importantly i am not getting stuck when turning against the wall if i was then the backdrop would still flash red excellent the other important thing to note is that my cat is still obeying the hitbox rules i can jump up but there's no way i can get stuck on his whiskers anymore but hold on a moment do you see what i see boy do we have a problem here our player can now apparently walk in mid-air this looks really bad news and it's obvious enough why it's happening let's temporarily remove the last switch costume yeah look we aren't standing in midair at all no the corner of our previously invisible hitbox is resting on the edge of the platform pop the switch costume back well we know why it's happening but what can we do about it click back into the player's costume tab to ensure our player cannot stand on things to the side of their feet we need to shrink the hitbox width to be no wider than our player's feet also while we're at it we can bring the bottom of the hitbox up a little to help prevent our player's feet hovering above the ground and lastly bring down the top edge say to just above his eyes this allows us to fit through slightly smaller gaps great select the cat we grouped it earlier making this task easier and delete it sorry scratchcat this leaves us with a smaller and simpler hitbox i'm excited to give this a test click the green flag okay yes notice right off at our player's feet are well embedded in the floor you may like this look or you may want to make some adjustments let's see if i can still walk in the air oh yeah supad this problem is gone and i fall right down as i might expect and i can collide my head with the platform from underneath last check walk over to the left and you can see that my head can overlap the walls quite a bit now this is just how things are going to work for the time being and you may actually quite like how it looks in a later episode we will see some advanced hitbox tricks that will improve things further and i'm dead excited to get on to that so let's press on coming back to our players feet then we can now tweak the bottom of the hitbox to change how far from or into the ground our player's costume appears check that out yeah cool our feet are nicely placed on the ground but jump up here ah this is why we needed to check up here we seem to be hovering slightly above the ground still so just in case you had any trouble drawing a good hitbox you'll find i made one for you it's at costume 20 and is named hitbox you'll also notice that there are a number of other interesting hitboxes in here but you'll have to just hold yourselves in anticipation because they are not for this episode we can switch to using this preset hitbox so i'll delete my big hitbox costume and then in the code find the when i receive tick first script switching to the costume hitbox excellent well all this talk of direction and rotation and yet our platformer has neither yet it's so easy well i just wanted to put it off until we had the rotation styles fixed in place so find the define controls left and right and when the left arrow is pressed drop in a point in direction negative 90. and of course for the if right arrow pressed we point in direction 90. click the green flag we are on to a winner this is really looking smart being able to change direction at last we can run jump all over the place with confidence that our hitbox is in place and so finally we are in a good place to begin animating our player 2. we'll begin with scratch cat's run cycle here they are in the costume editor to keep track of the animation i like to make a new variable named frame for this sprite only this will hold the animation frame number we want to animate only while actively walking so i'll drop a change frame by one into both the if key left pressed and right press scripts like so both of them want to add one this time a negative number would actually play the animation backwards now come back to the define set costume script remember i said we'd use this for the animations well now is the time we want to switch the costume to the correct ones for our run cycle let's take a look again at which ones they are the run cycle begins at costume one then in order goes through two three four and ends all the way down at costume 16. yep costume 17 is a jump costume so that's 16 costumes beginning at costume one we'll need those numbers back to the code we begin by switching costume to the first costume in the run cycle costume one and we'll be adding to this to create the animation so for now put in the variable frame running the project reveals the beginning of the animation this is promising but as expected our frame variable just keeps going up and after costume 16 it starts showing costumes that we do not want to show luckily there is a simple scratch maths operator block to fix the problem and it's called mod this is one of my all-time favorite blocks on the right we put the number 16 that's the number of costumes in our animation and on the left the frame variable what this does is prevent the value ever reaching the number 16. instead looping back down to zero again and again in a cycle perfect for creating a looping animation and test again and this is much improved are you getting that happy vibe i certainly am the frame variable is increasing all the time as i move but the animation is kept cycling around playing like a dream so now might be a good time to consider animation speeds depending on the number of costumes in your animation and the size of the sprite and the speed they are traveling at you may want to decrease the speed at which the animation is playing back let me show you first how not to do this if the animation was being handled in its own forever loop we might simply add a weight for say 0.1 seconds after the switching costumes you'll have seen this sort of thing before well you might think that this would work here but whoa whoa this is so broken that simple little weight has trashed our game take it out ah and we are back so why can't we add a weight here okay let me show you where a weight does work we need a separate forever loop that updates the frame variable and then we could update the costume and wait and if we run just that you can see this produces the slowdown animation we were after but in our platformer the frame is being updated in a main game loop within a tick broadcast and a tick broadcast like the tick of a clock must run very quickly any waiting in here is therefore not allowed so we must find another way to slow down our player's animations okay no problem we could instead slow it down by changing the frame by a smaller increment let's try 0.25 for quarter speed oh gosh there's a problem at every turn this does slow the animation down without the need for a weight but has revealed a small glitch in the run cycle i'm glad we saw this now though so we can fix it quickly when we switch a costume to say number 16 it's obvious that we get costume 16 on the stage but what if we set it to costume 16 and a half scratch in its wisdom rounds the number to the nearest whole number and that would round it up to 17. so that's where the glitch costume comes from to fix it we just need to always round the number down instead so we do this with a floor operator wrapping around the frame or the mod like so and yeah we now have a stable slow animation we can adjust its speed by setting the size of the increments in the change frame block excellent okay enough of that throw away that forever loop what i want to do next is bring back the player's idle pose so that we can stand still once the left and right keys are released we could possibly look at speed x and switch to standing when it's close to zero but this would also introduce glitches as we change direction instead we will make a change such that frame is set to zero when we finished moving in that case let's use an if else checking that frame is greater than zero if so then we use the run animation but otherwise simply switch costume to stand next find the define controls left right script there's a few ways we could get frame to zero when all the keys are released but to avoid repetition of code i'd like us to make a new variable key x for all sprites sometimes i call this joystick x then at the top of the script we set key x to key right arrow pressed subtract key left arrow pressed key right arrow pressed subtract key left arrow pressed if i run the project you can see that when i press the right arrow key the variable key x becomes one when the left key is pressed it becomes negative one and when no key is pressed it remains at zero this is crazy useful way of storing the key presses because now we can code like this add an if else and when key x is equal to zero this means neither the left or right key is pressed so we can set frame to zero yay that was our goal to set frame to zero when no key was pressed excellent next in the else either the left or right key has been pressed so we can borrow one of the existing key press scripts from before all we need to do is flip the direction of travel based on key x since key x is one for right and minus one for left we just multiply acceleration by key x and do the same for direction please don't forget though to restore the set speed x here back to the bottom of the new script before we find and delete this old script and now let's give that a test okay what do we see scratch cat is once more standing upright that's great news and his running animation nicely starts up as we run around what i don't particularly like is that when i release a key the player stops animating but continues to slide across the floor this makes things look uber slippery an effect that may suit some games but i'd prefer to make this better we'll start by taking a cue from the real world physics stopping the player dead when they slow down enough when no key is pressed add in a new if else block check that the absolute abs value of speed x is less than one this means that speed x is between negative one and one that's really quite slow at this point and since no key is pressed we are going to bring the player to a sharp stop by setting the speed x to zero let's see if that worked oh what oh gosh something is so wrong i cannot move at all well bother i'm sure the scripts were right oh yes i know just click the green flag again there's nothing wrong here it's just that editing the scripts with my project still running caused speedx to get set to an invalid value restarting things set it back to zero and from then on it was fixed phew what a relief so looking at scratchy's motion things are improving the sliding is a little less severe but only just the pose while we slide is also no longer the idle one but we're not quite finished with that yet how about we give them a slight walk animation while they slow down in the empty else change frame by 0.5 that will give them a half walk speed while they are sliding to a stop and let's see oh yes look at that it's beautiful isn't it crazy that even though the movement is just the same as before a little bit of animation has transformed it from looking slippery to being quite natural amazing i love it things are coming along great the final touch is to address our players jumping and falling actions at present you can see the player continues to play his run cycle while in the air this is not hugely realistic and we can do better scroll up to the define set costume script once more now while jumping the jumping costumes should overrule all the other animation effects so make a space for the new scripts right after the set rotation style detector jumping using if falling is greater than one and then simply switch the costume to let's see uh jump01 we attach the other scripts below lastly put in a stop this script after setting the jump costume this prevents the other scripts running while we are jumping can we test this sure we can well that was easy boing boing notice that not only does the jump costume show when we jump but also when we walk off a platform if we look in the costume editor we actually have a second costume that may be better suited for the downward phase of a jump its name is run underscore j2 catchy name using another if else we'll check for speed y being greater than zero that means we are traveling upwards the stop script can move to under this if else and while moving up we can now switch the costume to jump the whole script can be returned in here and then lastly set the costume to that run j2 in the else for when we are falling down great i am feeling really good about this run the project jumping has never looked so good we often spend a lot of time in the air in a platformer so the extra falling costume helps to make things look more dynamic well we are almost done for this episode but there's one crucial bug that we still need to fix that you've yet to see before i can show it to you though we need to rebalance our game by shrinking down the scratch cat to a reasonable size you can choose to make him any size you like but in my game he was supposed to be a lot smaller so click into the size input box and enter a size of 40. great wow so much smaller but that's okay i like it i just need to tweak a few of the variable values under the green flag setting jump force back to 12 and acceleration to 1.5 this setup will allow for much more interesting level designs as it gives us more space to run and jump around in i'm glad to say that we can now also get back onto scene 2. without getting stuck but not everything is rosy let's see if i can show you the problem i just need to run back and forth here hmm okay obviously more than i thought hold on it's going to happen there finally it did and we got stuck how is this possible and why does it only happen now and then these are very good questions since we were so careful in the last episode to fix this very problem all that we change are sprite costumes that means this must be costume related let's see things begin in the when i receive game loop our player's costume is set to the hitbox within the tick first broadcast next in the tick player broadcast the player is moved and the costume gets returned to the cat costume ah but then lastly the tick lasts his broadcast right the tick last is responsible for detecting the player moving off the screen and it uses the begin scene script and here it is this is where we are having the problem we are using the fixed collision in direction to get us out of any collisions after switching scenes which used to work fine but back then we were using a square costume now we would hope to be using the hitbox but no we just mentioned that by this point we have been returned to the cat costume as such depending on which animation frame we are on the fix collision script may not push us far enough out of the ground as it needs to as such when we appear on the new scene we are still stuck in the ground luckily that means it's a quick fix switch back to the hitbox costume and ensure to set rotation style to don't rotate move both of these in just before the fix collision in direction block afterwards we can use the set costume block to return the costume back to the correct costume once more so if all goes to plan that should have fixed our little problem we can test it by trying our best to cause the issue to happen again running back and forward back and forward like a crazy cat between scenes yep i think we're good fury that is a relief and on that bombshell i am going to leave you but i'm so stoked for the next video because it surely will contain some amazing new content but what will it be so many possibilities well you've all seen what we have in store i do hope you've enjoyed this episode please smash the like button and don't forget to subscribe to my channel to catch the latest videos we also have a channel membership for those most loyal fans to enjoy thank you members i've seen quite a number of those cool yellow badges appearing in the comments showing you've been with me for over two months wow how exciting so thank you for watching have a great week ahead and scratch on guys [Music]
Info
Channel: griffpatch
Views: 532,981
Rating: undefined out of 5
Keywords: scratch coding, scratch programming, scratch game, scratch 3, griffpatch, griffpatcho
Id: Y6jnwkwLhto
Channel Id: undefined
Length: 30min 8sec (1808 seconds)
Published: Mon Sep 13 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.