Unity 2D Platformer for Complete Beginners - #7 HEALTH SYSTEM

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video i'm going to show you how to create a health system that allows our player to get damaged replenish health and eventually die when the health reaches zero so let's go let's start off with a couple fixes first of all i want to take our fireballs and turn them into prefabs the advantage of that will be that if we ever want to change something in our fireball like let's say the speed the animation or the sprite you will not have to do this process for each fireball you can just open the prefab make the changes and all the rest of the fireballs will adjust automatically so to do that let's go into the assets folder and create a new folder for the prefabs now open the folder select the first fireball in the hierarchy and just drag it into the folder after you do that you'll see that the first fireball will have a blue icon which means it's a prefab now now delete all the fireballs that aren't prefabs then select the first one and duplicate it 9 times now you can select any of your fireballs and press the open button in the top right corner now let's change the speed to 20 and press the back arrow and see what happens you'll find that all of the fireballs have a speed of 20 now and the same will be true for every other change that you make so make sure to use prefabs whenever you're dealing with a large number of identical objects it will make your life a lot easier i didn't actually want to change the speed of fireball so i'll open the prefab again and change it back to 10. but let's say that you selected the fireball and change something without opening the prefab first what would happen in this case you can see that when i do it the speed field is actually written in bold now because the speed of this fireball is not equal to the speed of the prefab fireball so what are your options now well if you actually right click this field you'll see that you can either apply this change or revert it if you press apply it will substitute the value that you have in your prefab with a new value and if you press revert it will just cancel the change that you've made alright we're done with the prefabs but before you continue don't forget to choose the player object and drag in the new fireballs into the player attack script otherwise you'll get unassigned reference exceptions like this one next i want to introduce the concept of sorting layers to create a new layer just select the player and under the sorting layer field just press add sorting layer and basically we're gonna split all the objects into four layers background foreground player and ground so now that we have them created let's select the player again and assign it the player sorting layer next let's select all the background sprites and put them in the background layer and also make sure to select the backgrounds not only from room 1 but from all the rooms that you have now let's take care of a ground select all the ground objects and put them in the ground layer now let's select the finish flags and put them in the foreground layer and pay attention that the foreground objects will be rendered on top of the background but underneath the player and the ground when you're done let's continue with the walls these will also be on the foreground layer and do the same thing with the ceiling and the wall on the right this might take a bit of time but just have patience and get it done with now let me show you why it's a good idea to have sorting layers in your 2d game if you go into the sorting layers and just drag one layer up and down you can easily change the position of where this layer will be rendered and the changes will automatically be applied to all the objects in this sorting layer so you don't have to do this manually one by one and these are all the tweaks that i wanted us to do now we can jump in and create the health system go into the scripts folder and create a new folder inside it called health and inside this new folder create a new script called health as well now choose the player object drag this new script onto it and let's open it up and start coding first of all we're gonna need a private float called starting health that's gonna determine how much health you have when you're starting the game and we'll also need a private float called current health that's going to contain the current health of the player now let's create an awake method and inside that let's make the current health equal to a starting help next let's make a public void called take damage that's going to take in a float parameter called underscored damage and the logic here is very simple would you subtract the damage from the current health value but let's introduce a safeguard to make sure that the health doesn't go below zero or above the max value and to do that we're gonna use mathf.clamp and the minimum value will be zero as i just said but the maximum value will actually be the starting health because we never want to have more health than we have at the beginning of a game and because we already subtracted the damage from the current health we don't need the line that we wrote previously so you can just delete it now we can check if the player is dead after taking damage or still alive and we will do that by simply checking if the current health is above zero the next step is to make sure that your players always know how much health they have and to achieve that we're going to need to display the health value on the ui somehow the first step in this process is to create a new object go to the ui category and choose canvas and i'm going to rename my object to ui canvas just for the sake of clarity next we need to make sure that our ui is scalable and to do that we're going to use the canvas scalar component and set the reference resolution to a standard 1920 to 1080 and the match rate to 0.5 now you probably noticed that when you created a canvas an object called event system also appeared this object was created by unity automatically when you create a canvas and it's responsible for detecting the inputs making your buttons work and raycasting so it's important don't delete it but i also don't want it to take away space in hierarchy so i'm just going to hide it underneath the ui canvas now double click the ui canvas to focus on it and create an empty object inside it that we'll call health bar i want this object to be stretched on the entire screen and to do that you need to open the anchor presets menu hold alt and press this button now click on the health bar object right click it and go to the ui section and select image i'm going to call this image health bar total and explain why in a minute bear with me but now let's go to the sprites folder and let me show you which image i want to use and i'm gonna put the link in the description so you can download it too so for the health bar turtle object i'm gonna select the image with these 10 hearts and drag it into the source image field then i'm going to tick the preserve aspect checkbox and press the set native size button now take the image and drag it into the position where you want it to be placed in my case it's the top left corner once it's there start adjusting the size and remember that you can always go into the game window to see how it will look inside the game when you're happy with how it looks go to image type and select field this is going to allow us to change the fill amount of the image which basically will allow us to create a health bar but as you can see right now the fill method is set to radial which is more suited to a circular image so let's change that to horizontal and now if you try to change the fill amount i think you'll figure out pretty easily what we're trying to achieve here i think it's a good idea to start a game with three hearts so let's set the initial fill amount to 0.3 then choose the color of the image and set it to black now select the object in the hierarchy just to make sure and press ctrl d to duplicate it rename the new object to health bar current and change its color back to white so now your players will reliably know how much health they had in the beginning of a game how much they have currently and how much they've lost the next step is to go to the health folder and create a new script called health bar that will be responsible for updating these images and this script will have three references the first one to be player health the second one to the total health bar image and the third one to the current health bar image and we'll need two methods start and update and because we want the current health bar to be updated continuously we will put the current health bar fill amount inside the update method to calculate the value of the fill amount we will need the player's current health but if you go into the health script you're going to see that the current health is a private property which means you cannot access it from other scripts and to solve this we can simply make it public but just making it public is a bad idea because someone from another script could modify your health and you would know about that so this is why i use these two access modifiers the get means that you can get this variable from any other script but the private set means that you can set it only inside this script so in this way we make sure that the current health is being changed only inside the take damage method which is exactly what we want now we can go back into the health bar and just access the current health and then we need to divide it by 10 and let me explain why let's go back into unity and select the current health bar object so we know that we want to start the game with the health value of free so inside the fill amount field just type in 3 divided by 10 and you'll see 3 hearts alternatively if you want a health value of 4 just type in 4 divided by 10 and you'll get 0.4 and on the ui you'll see four hearts so this is very straightforward now that we have the current health bar working we need to take care of the total health bar unlike the current health bar your turtle health bar will be updated only once when you start the game so let's calculate the fill amount inside the start method this time and as you probably figured it out the formula will be exactly the same and that's because the total health bar needs to hold the maximum amount of hearts that you'll have in the game right which is equal to the player's current health when you start the game great we're done with this script now let's go into the health script and put in a way to damage the player so we can see how the ui works i'll create an input method and inside i'll check if the e key is pressed if it is the player will take one point of damage now go back into unity select the player object and assign the starting health to be free [Music] also don't forget to select the health bar object that we created underneath the canvas and assign the health bar script to it and then drag all the relevant references inside the script when you're done press play and let's see the magic happen if you did everything right every time you tap e a red heart is going to disappear which is exactly what we want so we're done with this part now let's implement some player animations so it actually looks like the player is getting hurt or dies open the health script and let's delete the update method it was just for testing so here you see that we have two scenarios when the player is getting hurt and when the player is dead so we'll need two animations now to play the animations we'll need a reference to the animator so let's create that and if you look at the player object you can see that it has an animator component on it so we can just grab it by using the get component method alright next we will use the new animator reference to set a trigger for the heart animation and for the dye animation when you're done go back into unity select the player object and open the animator window and let's create two new triggers one called hurt and another one called die now go into the animation tab create a new animation find the player animations folder and call it hurt then press save now go into the animator tab again drag the heart animation to the side and create a new transition from any state to hurt we need to assign the condition for this transition and it's obviously the hurt trigger and also don't forget to go into the settings and set all the parameters to zero and also disable the exit time now let's create a transition from her to idle and in this case we will leave has exit time on and we will set the exit time to one and the rest of the parameters to 0. the next step is to go into the animation window again and create a new clip called die in this case we will create only one transition from any state to die when the die trigger is on we don't need a transition from die back to idle because once the player is dead he will stay that way until we restart the game now let's make sure that these two animations are not looping by double clicking them and disabling the loop time after that select the player again open the heart animation press the red record button and choose the sprite renderer sprite for the first frame we'll use hertz01 and move the first frame to 5 milliseconds i'll tell you why shortly now position the second frame at 10 milliseconds and select heart 0 2 as the sprite now go back to 0 milliseconds and set idle 0 1 as the sprite here i added this extra frame because i want the players to be able to see more clearly how the dragon is going from the idle state to the heart state now create a fourth frame at 15 milliseconds and set herd 01 as the sprite and finally the last frame at 20 milliseconds and set idle 0 1 as the last sprite so now we have an animation that shows the dragon going from idle to hurt and recovering back to idle great we're done here now let's move on to the dye animation press the record button and for the first frame choose die zero zero one as the sprite now create a new frame every five milliseconds and increase the number of the sprite until you reach die 10. [Music] if you did everything correctly you should have 10 frames and the length of the animation should be 45 milliseconds and if you play the animation you'll see that our dragon will gradually become a red ball of energy which looks pretty nice let's go back to our health script inside the heart scenario we need to implement iframes but i'll leave that for the next episode inside the dice scenario i will grab the player movement component and disable it so that the player cannot move once they are dead and to make sure that the die animation doesn't play twice let's create a private boolean called dead now inside the else statement let's put an if statement that will execute this code only if the dead variable is false and after the code is executed set the dead variable equal to true in this way we can make sure that this behavior will not be repeated twice but we still have no proper way to damage the player so let's go back into unity create a new object call it saw and i'm pretty sure you understand what this one will do first of all assign a sprite renderer to the new object to find the image that we're looking for you'll have to go into sprites pixel adventure 1 assets traps and finally saw if you cannot find this folder you can also type in saw inside this search box but now take this off sprite and drag it into the saw object sprite render at first you might not see it on the screen but if you change the sorting layer to foreground you will immediately see it the scale is quite small so i'll increase it to 5 on all axes now drag it down until it's somewhere around this level i want half of it to be underground our next step will be to assign a box collider 2d to it and set it as a trigger now i want to make this thing look more menacing so let's add an animator to it and create an animation for it you can see here that we have all the sprites that we need to make it rotate so let's use them go into the animation folder and create a new folder called traps and inside this one create a new one called saw and finally create an animator controller called saw as well and assign it to the object now with the saw object selected go into the animation window press create and create a new animation that alcohol saw i think i said saw like a hundred times already this next part will be a bit tricky so pay attention and stick with me first of all open the folder that contains all the saw sprites now grab the animation window and drag it up so it's parallel to the scene and game windows now find the spinning source sprites and drag them one by one with a delay of 0.5 milliseconds between them there are eight sprites so when you're done you should have eight frames when you are sure that you have all the sprites and they are in the correct order you can just take the animation window and drag it back where you took it from if you press play you'll see the speed of animation for me this looks a bit slow and it doesn't look scary so let's make it faster select all the frames by pressing ctrl a and drag in the selection until you have a length of about 0 20. i'm pretty pleased with how it looks now so let's actually make it move and hurt the player go into the scripts folder and create a new script that i will call enemy underscore sideways and that's because they will move from side to side now take the script assign it to the saw object and open it up the first thing that we need here is the damage of the enemy so let's create a private float called damage and serialize it next we'll need an on trigger enter 2d method to detect collisions with the player and inside it we can just check if the collision.tag is equal to player if it is we can just grab the health component and use the take damage method to reduce the health of the player by the enemy's damage now go back into unity select the player and make sure it has the player tag assigned now select the saw and change the damage from 0 to 1 and if you have a rigid body component on this object you can remove it i edit it by accident now press play and run into the song and you'll see that every time when you touch the saw you lose one health and the hurt animation is being played and when you reach zero health the player will die and you will be unable to move if you see this error in the console you can just press clear and ignore it it's just some unity shenanigans so we created a nice saw it works it damages the player and it has an animation but it doesn't move so let's fix that now open the enemy sideways script again and add an update method first things first let's add a private float called movement distance which will indicate how far this object will move secondly we'll introduce a new float called speed which obviously will be the speed of the movement then a private boolean called moving left and two new private floats one called left edge and another one called right edge now let's create an awake method and inside we will calculate the left edge which will be equal to transform.position.x minus movement distance and the right edge will be exactly the same but it will be in the opposite direction so plus movement distance so now that we've determined the range of movement of the object let's get it to move in the right direction first of all let's check if it's moving left or right if it is moving left we will check if the x position of the object is bigger than the left edge which means that the object hasn't reached the left edge yet if the opposite is true we will say moving left equals false and we need to start moving the object to the right now we can take this piece of code and paste it underneath for the scenario when the object is moving right but because this is the opposite scenario we need to reverse everything first of all the comparison sign then change the left edge with the right edge and then in the yell statement change moving left equals to true now let's take care of a code that will actually move the object around so we will just take the object's current position and decrease its transform.position.x by speed multiplied by time dot delta time and maintain the y and z positions as they are now copy this code to line 33 and just change the sign from minus to plus to move in the right direction and that's it for this script we can go back into unity select the saw object assign a movement distance of 3 and a speed of 5 and press play and see how it works and if you did everything right you'll see that the saw is moving perfectly from left to right remember that you can also tweak the movement distance if you want to change the range of a saw or the speed if you want to make it faster or slower so now that we're done with this let's jump on to the final part of this video collectible hearts that will recharge your health we need to create yet another new object and call it health collectible first of all i'll reset its position to zero then add a sprite renderer component just as we did with the saw now go into the sprites folder and assign the hard sprite to this sprite renderer if you want to use this exact image i'll put the link in the description next we'll change the sorting layer from default to foreground and change the scale to 0.5 on all axes and just for the sake of demonstration i will place this heart next to the exit of room now let's go into scripts open the health folder and create a new script called health collectable also don't forget to select the health collectible object and put the script on it and also give it a box collider to the component with the trigger option now open up the script and let's get this thing to work the first thing that we'll need here is a private float called health value which will indicate how much health this will actually restore to the player next we'll add an ontriggerenter2d method to check for collisions with the player and if the object that we collided with has the tag player we're gonna grab its health component and use a method to increase the health but we don't have that method yet so when you're done typing switch to the health cs script and here as i said we'll create a new public method called add health that will take in a float parameter called underscore value and we're gonna use the same code that we used in the take damage method but in this case we're actually gonna increase the current health by the underscore value not decrease it by damage and that's it we can go back into the health collectable script use the add health method and pass in the health value variable and once the health is increased we need to make sure to deactivate the collectible because we don't want to be able to pick it up multiple times now we can go back into beauty and you'll see that i created another health collectible object off screen sorry for skipping this part anyway now we need to select all the collectibles that we have in the scene and assign a health value of one to all of them and that's it press play and see how it works you'll see that the first heart that we pick up will not add any health because our health is already at maximum but once you get damaged by the soil you can pick up the second heart and your health will be restored and that's the end of the video thank you for watching and congratulations on creating a health system stay tuned for the next episode in which we'll create the iframes and add a couple of new traps and enemies if this video was helpful make sure to hit the like and subscribe button and also consider supporting me on patreon because that would help me immensely in making this channel a full time thing and releasing more videos that's it go make some games now
Info
Channel: Pandemonium
Views: 13,194
Rating: undefined out of 5
Keywords: Unity 2D Platformer for Complete Beginners, Unity 2D Platformer episode 7, Platformer for Complete Beginners, unity platformer complete beginner, unity2d, unity 2d game tutorial, unity beginner tutorial, pandemonium games, game development for beginners, unity platformer, Unity 2D Platformer for Complete Beginners - #7 HEALTH SYSTEM, unity health system, unity health, unity3d, unity damage system, unity traps, unity enemy, unity health pickup, unity 2d platformer, health system
Id: yxzg8jswZ8A
Channel Id: undefined
Length: 23min 17sec (1397 seconds)
Published: Sat May 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.