Godot 4 Roguelike Course – Build a Complete Top-Down Action Game

#Godot 4 #Roguelike Game Development #GDScript #Game Design Principles #Procedural Generation #Combat Systems #Programming
💬 Chat with this Video
Ask anything about this video…
In this course, you'll build a complete top-down action roguelike game in Godot 4. Going from an empty project to an exported game anyone can play. You'll add dash combat with invincibility frames, five enemy types, and a boss, random floors of connected rooms, item builds, shops, and permanent unlocks. Over this course, we're going to be building this game in Godot, starting from a completely empty project. We fight through rooms of monsters, pick up reward after each fight, and carry it into the next room. And each floor ends with a boss. Every attempt is going to be called a run. When we die, the run is over and we start a new one. But, we keep a little bit of what we earned. That kind of game is called a roguelike. You don't need to have used Godot before. We'll set it up together and explain each new piece of code as it comes up. Most lessons will end with a short task called your turn. So, when you see one, pause the video and try it. Before we open Godot, though, let's work out what we're actually building. When creating a game before writing a single line of code, there's one thing that every smart developer needs to start with, the overall game structure. Not 14 or 20 different features, so get that idea out of your head for now. Before we start stacking different features and all the cool ideas that you may have, we need to decide what the design of the game is actually going to be first. Basically, what are we actually building? Because before we write a single line of code for this roguelike, I had a whole list of things that I thought I might need, but I ended up cutting a lot of it out. A lot of things that you probably won't see. And one of those decisions ended up being one of the main reasons that the whole design actually works, though. When you think of a 2D roguelike, you might immediately think of things that we might need. Movement, enemies to fight, items, an inventory of some sort, shops, upgrades, and so forth. Now, all of these sound reasonable, and you may not be wrong that a roguelike probably needs all these, but at some point going to hit a wall that I like to call the dependency problem. Now, imagine we make a slime that we can fight. Well, obviously this kind of depends on having a player to exist to fight it. Not only that, we need a way to fight. So, maybe our player will need a sword or some sort of projectile to fight it with. Then we decide the slime drops loot when it dies. Okay, cool, but where does that loot go? Well, okay, that means we probably need an inventory. So, we add an inventory, then we add upgrades, and those upgrades probably have to use these items in some way. So, we add a shop. Well, now the shop needs to know what items exist. So, we'll need kind of a database of all the items that exist in the game, what they're worth, and what the player owns. So, we'll add a currency as well because, well, we can't just get the things from the shop for free. We need some sort of currency to buy from the shop. Then we'll add item rarity, and yeah, so forth. So, you get the idea. One feature that started with a slime just turned into like 10 more. So, the point here is that we need some sort of visual map in our head or even a literally drawn out map that helps us figure out not only what we're making, but why. Everything that we create needs a reason. Why do we need items? Why do we need an inventory? Do we even need a shop? Every time you think of a feature to add or if you're following along in these tutorial videos, ask yourself, why are we making this? So, the first thing that we want to decide is, what is the player actually going to be spending most of their time doing? And And when I say player, I don't mean the actual player, I mean the user, you, the person playing the game. We need to basically decide what our core loop is. For example, in Slay the Spire, most of the game is you going into a room, fighting something with cards you have, and getting some sort of reward, getting stronger, and then just doing it all over again. If we simplify this down or just dumb it down, it'll look something like this. You enter a room, fight, choose a reward, get stronger, take a bigger risk, then enter another room. It's basically just a big loop. Now, the thing is, our game might not use that exact same structure. Maybe we don't even need rooms, but we still need some sort of loop that explains what the player is doing over and over again. And once we have that, we can make our first rule. If I can't point to where a feature affects this loop, it probably doesn't need to be in the first version of our game. For example, enemy variety changes combat. Okay, so that fits. Upgrade choices change rewards and progression. Okay, that fits, too. So, we'll add that. So, now instead of just saying, "This sounds cool. Let's add it to the game." we at least have a point to know where we actually start and add things when it matters. Now, why are we making a roguelike for this course? Well, we can build a short fight and test quite a lot with it. We can ask, "Does the movement feel right? Can we see an attack coming? Does this upgrade change how we play?" We can try those things without needing a whole story or a long level to set up first. Then, we can put the same enemies in different situations. A caster by itself might be easy, but what if we charge or block the way while it's shooting at us? Now, the combination changes what we need to actually pay attention to. Procedural rooms also give us more combinations to work with. But, that doesn't mean that the generator designs the game for us. We still get to choose the room sizes, paths, spawn rules, and what counts as a playable layout. Then, we can test what those rules produce. The same goes for difficulty. Players improving between runs doesn't fix an attack that they can't read a room or they can't escape. We still need to make those things work. So, the useful part here is seeing how a few systems change each other. We'll build them one at a time, then test what happens when we put them together. Now, at this point, once we've decided on a couple features and we know what the general game loop might look like, you might think that we're basically done. Just make sure that everything fits the loop and we're good. The problem is almost anything can fit in a loop if you try hard enough. You want to add crafting? Why? I don't know, progression. Well, there you go. You just added a reason. Fishing in your 2D roguelike? Well, why not? We can add some rare items. Blocking? Well, it's part of combat. Sure. A pet system? Well, that mean having a pet to fight you in your fights helps, so it works. Who's trying to win? If you do this enough times, uh we're suddenly back where we started and we're back to just listing out 100 random features. And technically, every one of these can have a valid reason or excuse for being in the game. That's not the issue here. The thing is, saying "Does this affect the loop?" isn't really enough. So, we need a second rule before we start basically adding new features. For the second rule, I like to have a maximum of three design pillars. Basically, if you could only pick three things that describe what you actually want the game to be, what would they be? And I don't mean stuff like fun, replayable, and cool-looking. Obviously, we want the game to be fun. That doesn't really help me decide whether blocking should exist or adding a pet to my game will help. I mean things like fast decisions, constant risk, build-defining choices, whatever actually describes the project, something like synergy. Now, the important part here is that the design pillar isn't just something that I hope the game feels like, it actually has to help us make decisions when we add things. So, if I say constant risk is one of our pillars, and then I add a feature that removes most of that risk, I need to change or cut it. Now, whenever we add something, we basically now have two questions. Where does this fit into the loop? Okay, even if it does fit, does it actually match the kind of game that we're trying to make? A really good example of this whole design problem coming into play is melee versus ranged combat. Let's say in this game that we're making, melee is our main way of attacking, but that involves a lot of risk because I have to actually get close to attack it. Now, that creates kind of more interesting problems. What if the enemy can't be stunned when I hit it? What if the monster's attack range is bigger than mine? What if just getting close is the dangerous part of the fight? Okay, so what if we add ranged attacks now? Well, now I can stand all the way over here and still deal damage. So, why would I ever need to risk getting closer? Now, that doesn't mean that we shouldn't add ranged attacks at all, but maybe they can just do less damage. Maybe ammo is limited, or maybe there's just some sort of punishment to the player when we used ranged attacks. These are basically ways of balancing these issues. Okay, but what if I add blocking? Now, blocking absolutely makes sense in a combat game because it fits the loop. It works mechanically. But now look how I play. Instead of attacking, dodging away, and repositioning, and deciding if I want to get close again, then attacking again, I might just stand here, wait for the enemy, block, attack, wait again, block, attack, and you see the idea. And if one of the things that we just said that we want is constant risk and fast decision-making, we kind of just broke both with blocking. Now, that's the weird part. Blocking isn't itself isn't a bad mechanic. It works fine. It just doesn't really work for a game that we're trying to make here because here we're trying to add constant risk and fast decisions. A mechanically good feature can still be bad design in decision-making. So, which of your features would actually survive this? And this is where one of the bigger decisions for this roguelike came in. Because I could have made a separate system for a lot of this stuff. So, maybe we need a difficulty system. Then another system controls how good the rewards get. Then another one decides how enemies scale. Then maybe we need something else that gives the player a reason to take bigger risks. And again, none of these ideas are necessarily bad. If you had any similar ideas to this, it doesn't mean it shouldn't exist. But the thing is, if we go back to the dependency problem, if we add a difficulty system, well, now what does it affect? Enemy health, enemy damage, spawn rates? Does it change rewards, too? Then if we added another system for rewards, now that needs to know about the difficulty system, too. Then maybe progression needs to talk to both of these. And now we're doing the exact same thing that we were trying to avoid initially. So, instead of asking what other system can we add here, I think the better question here is can one mechanic handle a couple of these jobs at once? Now, that is where corruption comes in, at least in our roguelike. The basic idea is that the player gets stronger, corruption can increase, too. Now, the basic idea here is it's a sort of punishment system for the player choosing to get stronger in a riskier manner. More corruption may mean more damage, but it also means more danger. You take more damage, the monsters get stronger, maybe things bad happen to the character when I have too much corruption, stuff like that. But okay, if I'm taking on more danger, why would I want that? Well, we can also tie in better rewards to it because obviously just giving the player corruption means nothing unless I actually have something to go along with it. So this way getting stronger lets me take on more corruption now. More corruption creates harder fights. Harder fights though can give better rewards. Those rewards make me stronger and so forth. You now kind of get the idea of the loop. Now we have this loop where all these systems are kind of feeding back into each other and that's exactly what we want, especially for a roguelike. So instead of having one system over here for difficulty and another over here for risk and another over here for reward, we're letting corruption handle a couple of these jobs at once and that's kind of the point. Cutting stuff doesn't necessarily mean that we have to take the game more shallow. Sometimes it just means we stop building three different systems that were all trying to solve the same problem. And now when you look at the finished version, you can actually see the original loop underneath most of the game. I go into a room, I fight something, that fight creates the risk, then if I win, I get some sort of reward. That basically changes my build. As my build gets stronger, I can start dealing with things like corruption. More corruption makes the next fight more dangerous, but it can also make the next reward more valuable. And then we basically do it all over again. The thing that I want you to pay attention to isn't how many mechanics are on the screen or how beautiful it looks, it's just how many of them are feeding back into the same loop. Because when one thing naturally creates a reason for the next thing to exist, the game starts to feel a lot more connected and just fun. All right, now at this point we could keep adding ideas, crafting, dialogue, more biomes, different classes, an inventory and so forth. Most of those could fit a roguelike. But take crafting for example. What does it need? Materials most likely. Okay, where do we keep those? Then we need recipes, a way to choose them and some reason to craft one thing instead of another. All of a sudden one idea just turned into several different systems before our sword could even hit an enemy. So we're going to leave crafting out of this version of this course. We'll also use one main visual setting. We'll save permanent progress and settings without building a complete mid-run save system. That leaves us more time to get the fight and room behavior actually working nicely. Shops are included because they connect what we're building already. The enemies can drop gold where a shop can give us another item choice. Burn and chill will fit because they change our attacks. Now, that doesn't mean that every other idea that you might have is bad. If you want one in your game, write it down it will need first. Then decide whether those requirements belong in our first version as well. At any point during the course, if you want to add something, do it. Give it a try. If you feel like you want to just follow everything until the very end, then of course do that as well. So, where do we actually start building? Let's say we start with corruption. It needs to change damage, so we need damage code. To test that damage, we need an attack and something with health. To test the attack properly, we need a player who can move into range and dodge afterwards. We can keep following those requirements backwards. So, we'll start with movement and aiming. Then we'll add health, hit detection, and attack timing. Once those work, we can make the enemies that approach, charge, or shoot. Then we'll make a room that tracks the fight, connect rooms into a dungeon, and add rewards between encounters. Permanent progress comes later because we first need a run that can start and end. The menus then connect those screens so we can play the whole sequence. Now, obviously we'll still go back and change earlier code, but at least each step will give us something that we can actually try first. If a feature needs three other systems before we can see whether it works, we either build those first or make a smaller test for it. We'll use that question throughout the course. What needs to exist before we can test the thing that we're adding? Okay, before we open Godot, try this with a game that you want to make. What does the player keep doing? Sketch that loop. Then pick a few features and ask why each one needs to be there. Now, choose one of those features. What has to exist before you can test that? I want you to give yourself about 5 minutes. Pause the video for 5 minutes and do that. You don't need a a design document. You don't need 20 pages of design. Just see if you can explain what you're going to build and what can wait. Your game might need an inventory. That's fine. But what is the player storing and why does it matter? Or maybe you want a long hand-built level. What small part could you make first to check whether it's fun to move through? If your feature needs something that isn't in the plan yet, add that requirement or move the feature to later time. The plan can change. We just want a reason for the next thing that we're going to build. First, we're going to need Godot itself. Go to godotengine.org and download Godot 4. And download the latest version of Godot. This course was recorded on version 4.7 and anything from 4.6 onwards should work the same way. Pick the standard version, not the one marked .net. Because we'll be writing our code in GDScript, which is Godot's own language. It downloads as a zip file. Unzip it and open Godot's app inside. There's nothing else to install. That's it. We also need the art for the game, the knight, the monster, and the tiles, and the sound. Download the course's asset folder from the link in the description and unzip it somewhere easy to find. Because in a minute we'll be dragging it into our project. All right, assuming we've already downloaded the .exe file for Godot, we're going to go ahead and double-click it. And your screen might look a little bit different, a little emptier with not as many projects. And that's okay. We'll go ahead and create the or create a project by hitting the create button. Once we're here, we can go ahead and select either the mobile or the compatibility. In our case, we can choose either because mobile is for less advanced 3D, usually meaning something like 2D. Compatibility is pretty good because if you want to use this on the web, uh exporting this to itch, then that is this is perfect. Then we'll go ahead and create, renaming your project and saving it wherever you want. Once we've done that, we can go ahead and minimize this just a little bit and basically find our asset. Here it is. Once you find your assets folder and find all the assets that we want to import, we'll go ahead and simply drag and drop it. After a couple seconds, you'll notice that it'll start to load. It might take a little bit and the the project might freeze and that's because the assets file is very large. But, just give it a minute and it'll finish loading. After a little bit, you'll notice that the assets folder has downloaded and imported inside of Godot. You'll know that it's imported properly because if we find a PNG file in here and I double click it, it should open on the right-hand side. Now, open project settings. Under display, window, set the stretch mode to canvas items and the aspect to expand. Our pixel art is tiny, so this lets the game scale up with the window instead of sitting small in the corner. So, before we can move anything, we need a Godot 4 project, our art and some controls. Now, the controls sound pretty simple. You press a key, move the player, but which key? Now, let's say D moves us to the right, but we also want the right arrow to do the same thing. We could check both keys in the script or we can put them under one action called move right. That is what input map lets us do. Our code checks the action and Godot checks whichever buttons we've assigned to it. We'll set up the course controls here, including a few we won't use until later. Then, over to the input map, type move_right, all lowercase, and hit add. Our code will look for that exact name, so the spelling here matters. Click the po- Click the plus and press D. It shows up as D physical, which just means the key in that spot on the keyboard. Then, do the same for move left with A, move up with W, move down with S, and dash with Z. That's our starting point. Now, let's finish off the rest of the controls. Now, at the moment, what we've done is add move right uh all the way to dash, but we also want to add a couple more things, and I'm going to go ahead and basically show you what we need before we move on, and this will just save us a bit more time in the future. All right, I've gone ahead and added everything else we need from quick attack, heavy attack, active item, interact, and codex. Uh the codex will be for much later, uh but that is just basically UI that pops up. Now, for the mouse buttons, these are a little different, um but go ahead and just add whatever the button numbers or uh letters you want for active item, interact, codex. Now, for quick attack and heavy attack, for the quick attack, we want to use the left mouse button. Unfortunately, I can't just click and it'll give me, right, like the input. I have to actually find it inside of the mouse buttons, the left mouse button, and then we want to go ahead and make sure we do the same thing for the right mouse button. We actually also have swap weapon, and that will be for Q. And now, that's it. That was all we need for the input mapping, and let's go ahead and continue. Okay, the project and input actions are set up. Some controls won't do anything yet, though, because we haven't made those features, but we have what we need to start moving. So, let's create the player now. Let's say that we drag our player image into the game. Okay, we can see it, but can it move? Can it hit a wall? The image by itself doesn't give us any of those things automatically. Now, in Godot, we can build that setup out of separate nodes. We'll put the sprite and collision shape under character body 2D, and save that whole setup as a scene. Now, when we add the player scene to main, we're making an instance of it. Basically, the saved scene tells Godot what to create, and the instance is the player we've added. You'll also see the sprite and shape indented under the player in the scene tree. That means that they're its children. So, when the player moves, they move with it. The very first thing that we'll do is create a new scene with a character body 2D as our base. Once we do that, we just want to rename it to player. We'll hit save, and we'll create a new folder called scenes and add our player into there for now. We now want to add our knight tile or knight image to the player. So, the tile that we're going to use for this is 96. So, we can go ahead and search it up, and 96 will pop up. This will be our player, but we'll immediately notice that our player is blurry. That is because inside of the project settings, we need to go and find the filter. So, if we type in a filter here, we will find that the default texture filter is linear, and we want to change this to nearest. This will allow Godot to actually render the pixels properly rather than smoothing everything in. Once we've done this, we want to go ahead and add a collision shape to our player. Make sure the collision shape 2D sits directly under player next to the sprite 2D and not under the sprite. You'll see a warning next to it because the node doesn't have a shape yet. The node only holds the shape. The shape itself is a separate piece of data called a resource, and we pick it up in the inspector. So, let's click shape and choose a new capsule 2D. Then, drag the handles until the capsule covers the bottom half of the knight. That shape is what bumps into walls, and in a top-down view, we want that to happen around its feet, not its head. Okay, now we want the player to collide with walls, but later we'll also have attacks that need to detect enemies. So, the question is, how do we tell those apart? Well, the answer is we just give them different collision layers. The layer says which category an object belongs to, and the mask says which category it checks. So, if our player is on layer two, a hazard needs layer two in its mask to detect that player. The collision shape still determines where they overlap. These settings determine whether Godot checks that connect at all. We'll name those layers as we need the com- or as we add the combat objects. We once we've done that, we want to go ahead and go to the player, the character body 2D base, go to the collision, and we're going to go ahead and select layer two, unselect one, and for the mask, we're going to do one and three. Okay, now we want to tell our player how fast to move. But, where do we put that number? We need to keep it somewhere our movement code can read, so we'll make a variable. A float can hold a decimal value. An integer holds a whole number, and a boolean holds true or false. Now, these are all different types of variables. Adding export lets us change that variable in the inspector. Then, we put the instruction into functions, which we can call whenever we need them. Return sends a value but back to the function that it called. The indentation shows which line belong together, and extends character body 2D means that we can use that node's existing movement features and add our own code on top of that. Now, we have a movement speed, and it included the decimal. So, how do we tell Godot that that's the kind of value that we want? See, colon float states the type. Colon equals lets Godot work it out from the starting value instead. So, after we declare it, we can use an ordinary equal sign to assign another value. Text in quotation marks is a string. So, move right in quotes is the name of our input action. A dot accesses something inside of an object, so velocity.x gets its horizontal part. Parentheses will call a function, like move and slide. That's a built-in function inside of our character body. And anything after a hash on a line is a comment for us to read, rather than Godot running the actual code. You'll notice that the coloring is completely different from any other code that we write. Let's say our damage function needs an amount. We can give that input a name in the function definition. Then pass an actual number when we call it. The named input is a parameter, and the value that we pass is an argument. Now, after the parentheses, the arrow shows the return type that we want. Our input function returns a vector two. Void means a function that doesn't return a value for us to use. We'll also make some variables inside functions and some outside of them. A local variable belongs to its block. A member variable belongs to the script instance, so it can keep a value between calls. That's where we'll keep things like the player speed and timers. Let's say we press right. Okay, what does that mean as a number? We want one on X, our horizontal direction, and zero on Y. Let's press down instead. We need zero on X and one on Y. We can keep those two numbers together in a vector two. In Godot's two-dimensional screen coordinates, positive Y points down. Positive Y points down. We'll subtract opposite inputs, so holding left and right cancels out. Then multiply the direction by our movement speed. Now, that will give us our velocity. Move and slide uses that velocity and handles the time step by itself, so we don't need to multiply it by delta again. We'll call it from {underscore} physics process, which runs in on physics ticks. {underscore} process runs with rendered frames. Those names are built into Godot, so the spelling here matters. There is a relatively big difference between the physics process and process, so just keep that in mind. There's a lot of explanations online that you could look into if you actually want to know the difference, but just know that physics and process will be for anything that involves some sort of physics. Next, we're going to go ahead and attach a player script. We're going to call it player controller and add it to our own script folder. Once you've gone ahead and attached the script, we want to go ahead and go over to the player controller. And we'll notice that we basically have a platformer script here. Now, we're going to go ahead and adjust this real very first thing we're going to do is replace all of this with one line where we say velocity is equal to get the move input times the move speed. And we have a couple of problems. The first one is that we don't have move speed. We'll do that or we will fix that by adding move speed. We're going to add this as an export and the cool part about this is if I go ahead and actually fix this error first, then we will see why the export is cool and we can fix that by adding the function get move input. And the idea here is that we're going to return a vector two with the input strength move right minus move left. That will be our x-axis and then for our y-axis, it'll be the move down minus the move up. Now, if I go ahead and save, we will see on the top right side, we will see the move speed that we just exported. And if I want, I could change this number. I'm going to leave it as 180, but feel free to adjust the number as you'd like. Now, if I go ahead and press this little button over here or F6 on our keyboard, there we go. We have now created a cool player that actually moves. Now, there's a couple problems though is the first one is that we're playing the game in our player scene. More than that, we have another issue, which is that well, the player is really small. Now, we could fix that by scaling the player. If we go to the transform and scale it, but we don't really want to do that. Instead, what we can do is just add a camera, a camera 2D. Once you've done that, we can go ahead and zoom in by typing in a four, and we will see the camera is much more zoomed in. When I hit play, I'll see my player. However, you'll notice that I can no longer move. It's not that I'm actually no longer moving, but more so that the camera is just following the player. So, I'm going to go ahead and just delete the camera 2D for now, as we're not going to use it for now. Now, what we're going to go ahead and do is create a new scene, and we're going to name this main. We'll save this. Put this in scenes. And I'm going to hit play right away and select current. Now, I'm not going to see anything. And that's quite okay. I'm going to go ahead and find my player inside of my folder, drop him in, and add a camera inside of here. I'm going to make the camera a child of the main and zoom in four. And now, when I hit play, I'll be able to move around without the camera following the player. Now, this is more of an example just to show you something, because we do have a problem with the player controller already. When I move to the left and right, it's fine, but when I move diagonally, I actually move slightly faster than I do going right or left or up or down. Now, this may not seem like a problem, but it does feel a little weird when I actually move around diagonally. Now, what happens if we hold right and down together? We get We get one on X and one on Y. So, the player will move diagonally. But, that diagonal is about 1.4 times as long as either straight direction. That's why we move faster. We can normalize it, which keeps the direction and makes its length one. We only want to do that when the input is longer than one, though. A controller stick pushed halfway gives us a shorter vector, and we want to keep that so the player can move slowly. Now, another issue is that aiming should not be a movement concern, either. So, let's take a look at how we can actually fix both these problems. We want to know whether the timer is zero, but if we write timer equals zero with one equal sign, we've just changed it to zero. Two equal signs ask whether the value matches. That's the comparison that we need. Less than or equal include zero as well as negative values. An if runs its indented block when the condition is true. And needs both checks to pass. Or needs at least one and not reverses the result. Plus equal adds to its value already stored. A default argument supplies a value when we leave it out of a call. And the short form one value if a condition else another chooses which value to use. Going back inside of our script here, what we'll do here is just assign this a variable. We'll say V for velocity. And then we will return V.normalized if the length is greater than one. Otherwise, we will just return V without being normalized. The idea here is that if I'm going diagonally, we're going to normalize the number. And this will essentially make it equal to as if I was going right or left. Because before this number could have been greater than one. So, we don't really want that. And now if I go ahead and hit play, I'll notice that my diagonal just basically isn't as fast. And it's not that it's not as fast, but now it matches the speed of my right and left movement. So, what happens when we actually add combat? Let's say there's an enemy over here. We're attacking it, but then I want to back away a little bit. Well, if the direction we're moving is also the direction that we're facing, the second that I back up, we turn away from the enemy. And that's kind of awkward. Why should deciding where we want to move also decide where we should want to attack? Those are two very different decisions. So, we can separate them. One direction controls where we're moving and the other controls where we're aiming. Now we can move left while still aiming right. We can back away from something without randomly turning our character around. And this becomes important once enemies actually start putting pressure on us. All right. Now that we've gone ahead and fixed the movement, we want to now add another Node2D and we're going to start adding our weapon pivot. From here, we're going to also go ahead and add a Sprite2D and this will just be a simple placeholder for now. So, use anything that you want. I'm going to go ahead and use the Godot icon, but as you can see, it's pretty big, so I'm going to go ahead and just scale it down a little bit. Now, from here, I want to go ahead and just move this guy to the right a little bit so we have a point of reference to actually point. Now, think of this as your weapon. This is where our weapon is going to be pointing. In order to actually aim our weapon, we first need to access our uh two icons here or two nodes. Now, we can move, but the sword still needs to point where we're aiming. We attached to weapon and pivot, so turning that node will turn the sword, too. Now, okay, but how does our script find it? The dollar sign followed by its path gets the node from our scene tree and on ready waits until the node setup is ready before looking it up. Now, how do we get the direction? Take the mouse's global position and subtract the player's global position. That gives us a vector pointing from the player to the mouse. We'll use its angle to rotate the pivot. Both positions need to be global here, so we're measuring them from the same origin. So, what we can do is actually drag this in. All we need to do is drag it in by holding control, shift, and drop it and it will say on ready with the pivot and the sprite. Once we've done that, I now have access to these two things. The function I'm going to want here in order to actually move this around is going to be update aim. Let's just make sure that the node the variable name is the same and all we're going to do is get the global mouse position subtracted to the global position of self. This is basically the player. We want to turn the sword by an angle. So, can we use 90 for a quarter quarter turn? Only if the a value expects degrees because 90 degrees is a quarter. But those rotation property uses radians instead. Now pi is half a turn. And tau or tau is a full turn. Basically 2 pi the same as 360 degrees. Angle already returns radians. So we can assign it straight to rotation. If we choose a value in degrees ourselves, we'll convert it with degrees to radians first. Rotated also takes radians and returns a vector turned by that amount. And we're going to take our weapon pivot. rotation and make it equal to the mouse .angle. This will literally just point our pivot towards our mouse. Now obviously we have this function, but we don't call it anywhere. So we need to go ahead and do that by adding it to the physics process. Once we've done that, we can go ahead and hit play. And now if you can see our weapon is actually staring at our mouse. And if I move around you can see that it's working pretty nicely. And there we go. We now have a player that is moving around with a weapon that follows our mouse. Now we do have a small issue which is that well, it's upside down which kind of makes it look weird. So what we can do inside of the update aim is if the absolute most go ahead and make sure the name here is right. If the absolute of the X is greater than four, we will take the sprite of the 2D and flip its H. Now we can go ahead and hit play. Now I realize this won't actually show any difference because our good dough icon looks the exact same if I flip it of the H regardless or not. So instead, why don't we actually just go ahead and give it the sword icon. All right, here we go. I'm also going to make sure I flip it. Here we go. And I'm going to make it a little smaller. Maybe 0.75 would make sense. And now you'll see a difference in why we flip the H. Once I hit play there we go. Now the bottom of the sword is always on the bottom. It's not a big deal, but if you would like that to be consistent, it makes a little bit of a difference. What if the mouse is right on top of the player? We're subtracting almost the same position from itself. So, we get almost no direction. Well, which way do should we point the sword now? What do we do? So, what we can do is keep a fallback for that case. That's separate from checking whether a number is finite. It calculation can also give us infinity or not a number, and that's what finite checks catches. So, we have a check for a direction that's too small, and another is an invalid result. Keeping the last valid position stops us applying a bad one. But, if that keeps happening, we still need to find which calculation caused it. So, what we'll do is add a last good position, save the last good position as our equal uh the tail global position, and then we will create a new function here called finite with a V, and we're basically going to check if the X and Y is finite, then what we'll do is check to see if not finite velocity, if so, then we will make sure the velocity is equal to zero. Then, after the move and slide, we'll add another check here to see if it's the global position is finite. If so, the last global position will be updated to the global position. And that's it. Now, we have our little knight guy with our little warrior our little sword here that can run around. Pretty cool. Okay, before we move on, try this. We're moving 100 units horizontally and 100 units vertically at the same time. So, do we travel the same distance as moving straight right for that time? Pause and draw the two directions if you want. Just see if you can actually answer that question before I answer it for you. Now, we travel farther diagonally. That vector is about 141 units long. To keep the same maximum speed, we cap the input direction before multiplying by speed. You can check it by timing straight and diagonal movements over the same interval if you'd like yourself. It is a small thing to see, but it is there. Cuz when you're playing the game, you're not thinking, "Wow, this character is moving 250 pixels. Amazing." No one thinks that. You usually think, "Can I get away from this enemy in time? Or can I dash away from them? Can I roll away from them? How long does it take me to cross this room? If something attacks me from over there, do I have enough time to move? How much space can my dash cover?" That's what you feel when you play the game. So, instead of starting with the player speed, I think it makes way more sense to start with the room. Let's say the room is this wide. And let's say we want it to take around 2 and 1/2 seconds to run from one side to the other. Now, we could technically calculate a starting speed, take the width of the room, and divide it by how long we want the player to take to cross it. And now we have a starting speed to test. And that will work. Now, what speed would let us cross this test room in about a second? Try working towards that. Use the same start and end positions each time, and time the crossing. Give yourself around 3 minutes to compare a few values. We're using 1 second as a target test, not as a speed that every game should use, though. If your room is wider, you'll need more speed to cover it in the same time. Distance divided by time gives us the speed for that target. After checking the number, play with that as well. Later, we'll compare it with attack ranges and enemy movement, because those affect how much space and reaction time that we'll need. Okay, we can walk now, but we also want a short movement burst to get away from attack. It's basically a dash. We could increase the player's speed when we press dash, but our normal movement code runs every physics tick. So, it could immediately replace the dash velocity. Instead, what we'll do is check whether we're dashing and run either either dash movement or normal movement. That's our state. When the dash starts, we save its direction and start a timer. That way, moving the mouse halfway through doesn't turn the dash. Speed controls how fast we move, and duration controls how long we keep doing it. We'll also use just pressed for the input. It checks the start of a press, whereas pressed stays true while we're holding the button. All right, so the very first thing to implement the dash that we need to do is, of course, add some variables. We need to add a dash speed and a dash duration. This is essentially how fast our player's going to go, and this is how long we're going to be dashing for. Now, the next part is the states of the player. We need to make sure we have the direction, a timer to make sure that we actually count from the timer to the duration, and a if statement or a boolean that tells us, "Hey, are we dashing or not?" At the very bottom of our script, we're going to go ahead and create a start dashing function. So, what we'll do is we'll create the function and return void. Inside of the function, we're very the very first thing we're going to do is get input. We're going to get input using the get in move input function that we created in the previous part. What we want to do is check to see if the input length is greater than zero. If it is, all we'll do is make sure we normalize the input. Now, if the length is not greater than two, what we'll do is get the mouse position and take a our dash direction and say, "Hey, we're going to dash to our mouse {dot} normalized only if the mouse the two mouse is greater than well, zero. Otherwise, we will just face the right direction by default. This way, we'll at least have some sort of direction by default, but obviously we do have a this. This basically just resets it to the right. Outside of this if statement, we'll need to also say is dashing is equal to true, and then we'll say the dash timer is equal to the dash duration. Now, you may be wondering, "Well, what about making it false?" Well, that will be for creating a function for end dash. And at the moment, all we'll do is set the is dashing to equal false. And notice the fallback. If he's standing still, there's no input direction. So, we need to take the mouse direction instead. That's right here. Without that, standing still and pressing dash does literally nothing, and the player doesn't conclude, "I have no direction." They conclude that the button is just broken. Any input that can silently do nothing needs a fallback. So, just keep that in mind whenever you're creating things on your own. We could start a number at 10 and subtract one every update. Once it reaches zero, we can stop dashing. That sounds fine, but how long is 10 updates? That depends on how often the code runs. We want a duration in seconds. Now, Godot gives us delta, which is how long or how much time has passed in seconds. But, obviously, the question is how much? Well, we can subtract that from the timer until it reaches zero. Then, we'll end the dash. The return below that stops the function call from continuing into the next block. The rest of the game it will keep running. We're just done with this function for now. Next up is the actual movement of the dash. To do this, we can, of course, add this inside of the physics update or process, but we're going to create a function for this to make things easy for us. So, to start, we'll create a update dash that passes through delta. This way, I'll be able to pass it through physics process later. And all we want to do is check to see if we're dashing. If we are dashing, meaning it's true, then we will say the dash timer is minus equal delta. And if the dash timer is less or equal to zero, then we will end the dash, and we will return outside of this if statement because we always just want to return. Next up is the actual input to see if I can dash. Now, this will be outside of this if statement, and we'll basically just say, "Hey, if I dash, then let's start the dash." Now, in order to make this dash work, we want to go ahead and go to the update aim right under it, we will add update dash, and then we'll add if is dashing velocity is equal to the dash direction at times the dash speed. Otherwise, we will set our velocity equal to the input movement times speed. This is literally just the move speed that we had, but because I have this equal to true or false, we don't want to have this being repeated twice. So, we can actually just remove this line because when I'm not dashing, this will always be true. Now, obviously we want to test this out, but if you haven't already, we need to go ahead and add the input direction or input map, I mean. So, I'm going to go ahead and add the input map dash, and I'll make this Z for now. Once I'm done that, I can go ahead and press Z, and you'll see we now have the dash working pretty nicely. At first, it might feel really good. We press the button, we move really fast, we can dodge out of the way. Cool, but okay, what stops us from doing this? Now, why would I ever want to walk? If the fastest way to move around through a room is to just dash dash dash, then the dash isn't really movement option anymore, it's just the new movement. So, we need some kind of limit here. Now, that could be stamina, maybe some sort of charge, maybe recovery animation. For this, what we can do is just use a cool down. Now, we can still dash when we actually need it. Maybe we're about to get hit, and maybe we're about to try to get around an enemy. Maybe we even want to close the distance really fast. But we can't use it to completely replace regular movement anymore. Okay, the dash has ended. Does that mean we can immediately do it again? Well, maybe we want a short dash, but a longer wait before the next one. So, the duration and the cool down need their own timers. Later, to show how much cool down is left, we'll divide the remaining time by the full duration. Subtract that one from one, and we can get an empty bar when we dash. Then a full bar when it's actually ready. Now, clamp keeps the value between zero and one. A timer node could give us the same ratio using time left and wait time. We're using a float countdown here because we've already got the timer code in our controller. Okay, all right. So, in order to create the cooldown for our dash, we now need to add two things: a cooldown variable and a dash timer that will allow us to essentially keep track of whether or not we can dash to an extent. In order to gate this, meaning we need to stop the dash from actually happening if I basically can't dash because of the timer, what we'll do is inside of the up key dash, is inside here we'll say if the dash timer is greater than zero, we'll reduce the dash by negative uh or we'll minus equal delta. Then, over here at the very bottom, we'll also just create the dash timer CD uh equal to the dash cooldown. Now, to order In order for this to actually work and make sure I can't dash, we'll actually add it inside of here as an and variable. We'll say and if the dash CD timer is less than or equal to zero, that means I can dash. Therefore, let's start the dash. Now, you can imagine that this will allow the dash CD timer to go below zero, and that is totally fine because at some point we'll just use it up and reset it. We'll also create a function here get dash ratio. This will essentially allow us to just get the HUD or expose it for the HUD. All right, that's it for the dash. Let's see if it works. All right, you can kind of see that I can't dash immediately. I'm spamming my dash button, but it's Yeah, again, it just doesn't dash immediately. So, that means our dash cooldown is working. Of course, if you want to increase it or decrease it, that's of course up to you. If you want to do that in the dash cooldown export, go for it. If not, that is it for this part of the video. Okay, we've added quite a bit at this point. Let's follow one button press. Godot checks our input action. We turn that into our direction and then multiply it by speed. But, if we're holding two directions, that vector can be too long. So, we shorten it first. Now, what happens when we dash? We save a direction and use that movement until the timer ends. Walking takes over again, but the cool down can stop another dash. So, if the dash goes too far, which value would you change? It's duration or speed affects distance. Cool down affects how soon we can use it again, and those are two different problems. And now we know where to look for each one. Set dash cool down to zero and play for 30 seconds. Then try 2 seconds. Try to notice how often you dash, whether you still use normal movement, and how long you waited for after using it. Give yourself about 3 minutes for the comparison. See, with no cool down, you may start using repeated dashes to get around. With 2 seconds, you have more time where walking is the only option. Keep the dash speed and duration unchanged while comparing them, so that way you can see what the cool down's change. We'll revisit the value when we have the enemies to actually dodge. The dash moves us out of the way. Okay, but what happens if an attack overlaps us during that dash? At the moment, movement alone doesn't prevent damage. We need to decide whether the dash gives us a short invulnerability period as well, though. Then we need a way to see when that protection is active, so we can test it when it's actually happening. Imagine we put a damage zone on the floor. We want to walk through it and take damage. But, if we make it solid like a wall, we can't enter it in the first place. So, we need to detect contact without blocking movement. That's what we'll use area 2D for. It's collision shape defines the area it checks. When the player enters, Godot it will emit a body entered signal and includes the body that entered. Now we need a function to respond to that. Connecting the signals tells Godot which function to call when the overlap happens. You can make that connection in the editor or in the code. We'll use connection so we can follow what happens when the player touches the hazard. All right, so our next concept here is to create a hazard. Because our scene is pretty empty right now, we want to create something that the player can run into. Now, what we're going to do is use an area 2D as a new scene. We'll go ahead and hit save and call this hazard.scene. We'll save it to the scenes folder. Inside of here, we'll also rename the base scene to hazard. We'll also add a collision shape as that will get rid of our other error. This error is going to tell us that, "Hey, we don't have a shape." We've added collision shape 2D, but Godot still wants a shape. Why? The node gives us somewhere to put one. It doesn't decide whether we want a rectangle or a circle. We'll give it a rectangle resource and set the width and height. A resource holds data that another object uses. Now, we'll see that again with textures and materials later. Moving the collision node changes where the shape is. Changing the rectangle resource changes its size. So, we'll go ahead and give it a rectangle shape 2D. We can zoom in a little bit. And I'm just going to give it a color rectangle for now because this isn't going to be a permanent addition. We're just going to use this as a temporary hazard in our scene. And because this scene is temporary, what I'm going to do is I'm going to add a script, but I'm going to say that it's built in. This will allow us to create a script, but it's not going to save anywhere. It's saved to the scene. Now, the advantage to this is when I delete this scene, the hazard scene, this script will also be deleted. Now, you can imagine this is not usually good for a lot of practices, but in our case, this is perfect. Okay, now what we have here is the extending to area 2D, which we already had. We are going to change the ready function to have the body entered.connect on body entered. Now, this is one way of connecting a signal, which is generally the preferred way. Another way is to go to the signals tab, and you can see here we have the body entered, which is right here. If I had double click this and connect it, you will see this little green icon over here on the left-hand side. This is one way of connecting, um but it's kind of connected both ways, which does work, um but I'm just going to go ahead and disconnect it from the hand the right-hand side. Now, the important part here is if a body enters this area, it'll print hit. So, now inside of our main function, we'll go ahead and add the hazard and hit play. And once I go into it, we will notice that nothing is happening. Okay, so the problem that we had was because of the collision layer. Um I remember that we actually changed this earlier, and this is where it actually comes into effect now. So, inside of our hazard or inside of our area 2D, we're going to want to go ahead and press mask two and layer two. Once we do that, now we will see the hit. Now, the general way that this works is essentially the layer our player is on the layer. If we want something to collide with it, we would need the mask as the second thing. So, if I went and go ahead and sell unselect those two, this should still work normally. We can even unselect the layer here because we don't really want this hazard to affect anything else. It's more so we want the player to get affected onto the hazard. So, the layer two is going to be affected or kind of detected by the mask two of this area. Okay. Now, the important part here is we want to test we wanted that to test to see if we can make our dash invincible. Okay, the player can touch the hazard, but what if we're dashing through it? We still overlap. So, the signal can still fire. We need a separate check for whether we're allowed to actually take damage or not. We'll store it in a boolean called in invulnerable and return without applying damage while it's true. The blue tint will show when the protection is active. We'll also give our player script a class name. Then the hazard can use it to check that body is a player controller before trying to read its invulnerable variable. Naming the class lets us recognize the type so it doesn't have to create another player. Now, let's actually make our dash invulnerable by adding a new variable, invulnerable uh is equal to false by default. Now, we can set this inside of the start dash. At the very bottom here, we can just say invulnerable is equal to true. And then similarly, we would want to end it at the end dash. We want to set it back to to false. Okay. Now, inside of our hazard, what we'll do is go to the script on the left-hand side here, and we'll just say if the body is a player controller and body is invulnerable, then return. Now, there is a problem here, which is that could not find type uh player controller. That is because inside of our player script, this is just an extend node. Now, let's play with the concept of class name. Class name allows us to essentially create a node with whatever I name it. So, in our case, I can call it player controller. So, now we're checking essentially for a node type called player controller. So, imagine we actually don't have to imagine. We can actually search up our player now and see that we have the player controller. Now, this is more than just a character body. This is the actual script that we wrote here. And which is pretty neat. But the biggest advantage here is now I can check to see if it's a player controller type and if that body has invulnerable. If it does, um and it's true, then we'll just return, meaning I won't ever hit this print. So, now we can go ahead and test it. If I walk through it, should be normal. But if I dash through it, you see, yeah. Yeah, I'm not that good at it, but you can see that if I dash, it doesn't uh print the hit once I dash. I also just realized my cooldown might be a little long. Uh actually, 0.6 is fine. But, that's it. Now, here's a problem, which is that when I actually dash and walk through, you can't really tell which one's which. Like, you If you're watching right now and you're kind of unless I actually tell you when I dash, it's hard to tell when I'm dashing and when I'm invincible, when I'm not invincible, etc., which is kind of a problem visually. So, if you as a player can't really see what's happening, then the game kind of has an issue. If we sometimes take damage during a dash, we need to know why. Did the protection end before the contract? Did we never set the flag, or is the hurt box checking a different value? Changing the tint while invulnerable helps us compare the visible timing with the damage check. It doesn't create the protection itself. We'll test a contact while the flag is on and another after it ends. Then, check the color changes with those same values. We want the player blue while protected, then back to normal afterwards. So, how do we describe that blue in code? Color takes red, green, and blue, or RGB amounts, plus alpha for how opaque it is. That's the very basics of color in code. For these tints, zero means none and one means full. If we leave alpha out, it will just default to one, which is the most opaque. Modulate multiplies the sprite's color by that tint. So, white keeps the original color, and lowering alpha fades the image. The invulnerable boolean will still control the damage. The tint just lets us see when that protection is on. So, what we'll do is when we set the start dash invincible, or invulnerable, we will say the sprite module, modulate, sorry, uh we'll make it equal to color, like blueish. Now, you'll notice though that the sprite gets aired. We need to get access to our sprite here, which is actually sprite 2D I just realized. We'll make sure that it says sprite 2D. And then on the bottom we'll set it back. But what what we can do here is say color.white. Now a pale blue will just add a specific color that allows us to distinguish between the dash and not. Oops. And there you go. You can kind of see the little visual that it turns green. But of course we do also realize that the sprite 2D is the weapon. It's not the tile of the player itself. So let's also add that. And if you'd like you can obviously add this. So as a kind of final step I'll go ahead and just modulate this as well. And that's it. Now we have both the player sprite and the weapon turning into these colors that we set. If you'd like to set a different color then go for it. But this is a pretty good color for me at the moment. The player is inside the hazard. Both collision shapes are enabled and the signal is connected. The player is on layer two but the hazard's mask only check layer three. So what would you change first? I'd add layer two to the hazard's mask. The player is on that layer so the hazard needs to check it. The shape and signal can both be set up correctly while the mask prevents the contact from being detected. Okay, here's how long we dash and here's how long we project that damage. Do those have to end together? Well, they can but they're two different rules here. If we shorten the protection we can also still be moving in the dash after it ends. If we extend it we stay protected briefly after it stops. We'll show that with the player tint so the protection matches something visible while we test it. In a test copy try extending the invulnerable window a little beyond its dash. Keep the tint active for the same interval. Give yourself about five minutes then compare contact just before and just after the protection ends. Restore the course timing when you're done. With a longer window, we have more time where contact won't cause damage even after movement stops. Check whether the tense still shows that correctly though. A longer window might be useful in another game, but here we want to choose it deliberately and test it against attacks rather than assuming that the dash animation tells us when we're safe. Okay, now that we have a good working game, uh relatively so, we have a problem which is that right now the player kind of can move out of the screen. Now, a way we could fix this is stop the player from going outside the screen. Uh but a better fix is probably to change the camera so that it can actually do something and follow the player. Okay, we could put the camera straight on the player. It follows perfectly. But now every small movement and especially a dash moves the view immediately as well. Do we really want all that? Well, not really. So, we'll try a smooth follow and small offset towards the aim direction. Then test whether we can still see the space that we're moving and attacking into. To do this, we'll go ahead and add a script to it called a player camera. I'm going to go ahead and add it to my scripts folder. We want the camera to follow our player. Well, obviously, it needs to know which node that is. So, we'll store the player's path. Look it up and check that we found something before trying to follow it. A safe look up gives us null if the node isn't there. Now, instead of moving the camera straight to the player, we'll use lerp to move partway there. A value of 0.5 picks the halfway point. Repeat that from the camera's new position and it gets closer every time, which gives us a much smoother follow for the camera. Once we've done that, we want to go ahead and add a couple variables. First, we'll export the target path and follow lerp. This is a number, but the important one here is the node path. We'll set that in just a second, but the important part is to keep note that this is an exported node path. We also have the target, which is slight a slight problem because we don't have a target set yet. So, we're going to have to do that. To do that, what we can do here is call a function called make current. Uh it forces this camera to become the current live one. So, essentially, if you actually go over here and look at enabled, it's as if we're just turning this on. Okay. Uh once we've done that, we can now uh say if target path is valid, then what we can do is say target is equal to get node or null. Now, this is kind of important because if I just did get node, this could error very often, uh which we don't really want. We don't want an error to get pulled into our game even by accident. Uh and we'll get the target path, which we'll get in just a minute. And then, what we can do is if target and instance valid, uh if the target is valid, then we'll get our global position equal to the target's global position. Now, this is just the ready. So, keep that in mind that this is just the ready. Now, the important part is basically just do this again, but in the process function. However, what we're going to do is lerp to the global the target's global position. So, it's as if What this basically means is we're going to take our global position and essentially move it, so lerp is moving it, to the target's global position at a speed of this. So, what this is going to do is uh multiply delta by follow lerp. Okay, now the important part is the target path, so let's go ahead and close this out. And if we go ahead to the target path and assign, we can go ahead and assign the player. This is essentially taking our target, which is player, and finding the path to our player. Now, when I move, you can see that I can and with the player or the camera following. But, you'll notice an immediate problem problem, which is that it's just stuttering, right? Um the idea or the problem here is it's kind of an FPS problem. Um essentially, the follow lerp * delta isn't actually frame rate independent. It just looks like it should be. Uh you'll also notice there's kind of a not really a bug per se, but a um gameplay annoyance, I'll say, uh with moving and the mouse. Moving halfway to the player every frame sounds reasonable, but what if one computer draws twice as many frames? This is a very common thing. It's not just a hypothetical question. Well, now it moves halfway twice as often, so the camera catches up faster on that computer. Basically, you would have almost two different gameplay visuals on two different computers. We can account for that overlap's time with this exponential calculation. The follow value controls how quickly the gap gets smaller, and delta tells us how long this update took. With a fixed target, two short updates should produce the same amount as one update of their combined duration. You don't need to memorize the expression to use it. Just remember why it's here. We don't want to We don't want the follow speed changing with the frame rate. Other causes of camera jittering still will need their own check later. Okay, so to fix this, we can replace this line here with global position equal global position.lerp. We're going to do the exact same thing. Uh and we're going to go to here. The main difference here is that we're going to change the speed 1 - exponential of - follow lerp * delta. This will give give us a frame rate independent easing. Okay, we can move the camera partway towards the player, so it follows more smoothly. Then we want to see a little further towards the mouth, so we add a small aim offset. But quickly moving the mouse can make that offset jump quite a bit. It basically looks very buggy when technically it's not. So we'll smooth the aim offset as well, then use it when calculating where the camera should actually follow. At the top, we will also add three new variables, four new variables, sorry. Aim lead, aim lead max, aim lead lerp, and lead. Then, we're going to go ahead and replace the process function with this. Now, it is a little different. We're essentially creating a new variable for our goal down here. And what this is is the target's global position plus the lead. And if we kind of go backwards, the lead is going to be the lead lerp want lead with the exact same thing that we just did. It's um the 1 - exponential of - aim lead. And if we go up to the top here, the want lead is only if the aim lead is greater than what zero. If so, then want lead will be equal to the get global mouse position minus the target.global_position * aim lead. Okay. Let's say we get hit and want the screen to shake. We could move the player around, but now we change where the player can collide with things. We only want it to shake the view. So, we'll change the camera's offset instead. We'll keep a value called trauma between zero and one and add add to it on a hit and reduce it over time. Squaring that value makes the smaller amount much weaker. So, a small hit doesn't shake the camera as much as a big one. A changing wave A changing wave moves the offset back and forth. We'll use a sine wave for the sprite bob as well. But that only moves the image. The player's body will still follow our movement code. That's a very important difference. Now, this is pretty cool, but we can also add a couple more things. We can add trauma shake, or just shake as you would like to say. We'll do this by adding a couple variables, max offset, max roll degrees, trauma decay, trauma, and time. Now, if you'd like to call this shake, you're more than welcome to. Now, what we're going to do is add a We'll add at the bottom here is add a function that is We're going to be able to call it. So, add trauma amount. This will essentially tell us, "Hey, we're going to add this trauma to our camera." Essentially shaking the camera for this amount. We'll also create this function noise, which just allows us to do a little bit of tuning to our time and seed offset. Now, in order to make the shake work, this gets added to our process. So, essentially if our shake is happening, then we'll actually shake it. If not, then nothing happens. It'll look something like this. So, what we'll do is add time to delta. We'll add our trauma equal to the max float of the trauma minus the trauma decay times delta to zero. We'll get our shake is equal to trauma times trauma. This is essentially just squared. And then, if the shake is greater than zero, that is the important part, then we're going to offset our camera. That's basically it. We're going to also take our rotation degree and equal to make it equal to the max roll degree times shake times the noise. Now, if none of this is happening, this is also the important part, is we're going to make sure offset and rotation degrees is zero. This basically just means we're not shaking the camera. Okay, now to make this or to test this, let's add a add trauma inside of the ready function. Go ahead and close this and hit play. And we'll notice it doesn't really work right away. It kind of did, but it's a little too short. So, let's try 1.2. And there we go. That was our shake. You can kind of see it. It's a little hard to see because obviously this isn't supposed to be in the ready function, but we're adding it here just to test it out. Another way we can test this out is inside of the hazard to trigger it through the camera. So, a little a way to kind of do this by cheating is to drag in our camera and say we're essentially getting getting the node of the camera and saying add trauma 1.2. And if I walk into it, you'll see my camera shakes. All right, and there we go. I'm going to go ahead and delete this though. We'll also test the aim offset separately. If moving the mouse quickly makes the target jump around, changing the camera follow alone may not give the result that we want. Smooth the offset limit how far it can move. Then compare the combined behavior for the camera. Okay. Now, in our player, we also want to complete our controller, we also want to add base sprite scale and bob time. Essentially, we're going to make our player feel alive a little bit. So, what we'll do first to start is get our base sprite scale and make it equal to our uh player sprite .scale. Now, essentially, we're going to bob our player as he walks. So, to do this, we'll add a new function called update body juice. So, think of it as juice for the body. Okay. If we're dashing, we're going to return because we don't want to apply this to the body unless we're just walking. Next, we'll get our frequency equal to 13 if moving, otherwise, we'll have it to three. We'll have the amplify to 1.6 if moving, otherwise, we'll have it to 0.8. The bob time is going to be equal to the delta time times frequency or plus equals, I'll say. Uh and then we'll get our sprite.position.y equals sign bob time.amplify or times amplify. This will essentially bob us up and down a little bit uh for our player position. Now, the important thing to kind of realize here is that we're editing the player sprite, not the player itself. Now, to actually make this work, of course, we want to go ahead and head over to our process uh physics process and let's add it right here. Update body juice with delta. Uh we'll also get the move input. length only if it's greater than point one. Okay, so let's test this out. Hit play. And you'll see my player is bobbing up and down as I move. This basically gives us this illusion that we're walking. Because of the sprite doesn't have any animations, this essentially acts as our, you know, animation. Okay, try making the movement feel heavier while keeping the same maximum speed. You could experiment with acceleration and deceleration or change the spice movement reaction. Give yourself about 10 minutes here. Check both on how it looks, how quickly the body starts and stops because those aren't the same changes. Acceleration is one option. Move velocity towards the target instead of assigning it immediately. The maximum speed can stay the same, but a short room crossing may take longer because we need time to reach it. Visual bob or squash can change the appearance without changing the time travel. Compare them separately, then keep the behavior that you intended. Okay, at this point we've got the player moving and dashing, but here's something worth trying before we add more to it. If you hid my code and wanted to change how that movement worked, would you know where to start? Well, you might or you might recognize everything when I explain it. But then you get stuck when you're trying to make your own decision of what to actually write. That's a useful thing to find out when the idea is still fresh and that is why I built coding quest. It's a site where you learn Godot and GDScript by actually working through coding quests. You get a task, write real GDScript in the browser and use code checks to see whether your attempt passes or not. So, you have something specific to work on. If part of the attempt doesn't pass, you can look at that result, go back to the idea and try again. Now, the video is useful for seeing how everything fits together. The site just gives you a place to have have at it yourself with a task and a check on the other end. For this game, there's a 2D roguelike campaign. So, if you wanted to just follow this course along on my website, you can definitely do that. It starts off with building the controller, then takes you through the systems that build up the game. The first controller quest is completely free for free, so you can go check it out right now. You don't even need to make an account. The full campaign is part of the paid guild quest membership, but you can try that first quest before deciding if you want more. There is also a 7-day free trial, so you can just go try that out. So, follow the coding quest link down below and try a lesson. See what you can write before actually coming back to my version. We've got a player that we can move around. Now, if something hits us, what changes? We need health before we can actually build a fight. So, let's do that. So, the player walks into the hazard. Does that automatically mean we should take damage? Well, no. First, the shape and collision setting let us detect the contact, then the signal calls our function. And that function checks whether we're invulnerable or not. Only after accepting that hit should health change. The camera can shake around all of this, but it isn't moving the player's body. Now, we're putting health in a component so other objects can use those same rules. If a hit looks wrong, follow that you just follow that sequence. Did we detect it? Did we accept it? Did health change? Once we know that, we can check the display instead of guessing from whatever looks wrong on screen. So, in this chapter, we're making the fight actually work. First, something that can take damage, then a sword that can hit it, then the timing of a swing, and then last, the feedback that tells us a a hit actually landed. To test all of that, we'll make a training dummy, a target that just stands there and takes our hits. So, we can check the damage before we build real enemies. To make the dummy take damage, we could have just put a health variable in its script. This is very easy, we just give it a variable and reduce it. But, the player needs health as well, and later we'll have enemies with different max health and still need the same rules. We can't really go below zero, for example. We can't heal past our max, and we can't or we shouldn't be able to die twice. For obvious reasons, because what if dying gives XP or gold, right? Then it'll give that thing twice. So, we'll put those rules in one health component. Okay, we put a health component on the player and another one on the dummy. Are they sharing the same health value now, though? Well, no. Each one has its own value. They're sharing the script that handles that value. When something needs to deal damage, it calls that component. The component changes the value and emits a signal. The player and dummy can respond differently without needing different versions of the damage calculation. All right, so we want to create a new script here. And we'll call it health component. We'll go ahead and hit create. Double-click it to open it up in scripts. And I'm just going to pop it out here. Once we're in here, the very first thing that we want to do is make this into its own node. We'll do that by giving it a class name, similarly to how we did it to the player. Once we've done that, we want to go ahead and give it two new variables, a max health and current health. Once that is done, we're going to go ahead and replace all these functions with ready, damage, and heal. It's very simple. We'll basically just set our current health to max health. Damage will pass through an amount, same for heal. Uh and these just work the exact opposite. So, one will subtract the amount, and one will add the amount to our current health. One note to think to just mention is we're extending node and not node 2D because this node that we're creating, the health component, should should not have a position 2D or 3D or anything of any sort. We only want the very basic components of a node. Now, we have a hazard already, but why don't we go ahead and create a character body 2D and rename it to dummy. We'll go ahead and save this inside of our scenes. We can go ahead and add a sprite and which one we want to do is well, just any sort of dummy. A cool dummy would be maybe a barrel. That could be neat. Or of course, you could use one of these guys, wizard, little guy. Whichever one you'd want, but these all start around a 009. So, if you want to pick whichever, go for it, but I'm going to be using a barrel. I think that kind of makes sense. And then we're going to go ahead and add a collision shape to our dummy, add a shape to that dummy, and give it to make sure that it actually fits. Once we do that, we'll go ahead and add a built-in script to this, and I'm going to replace everything with this code. We're going to basically make an on ready variable that is a health component node, and it's going to be equal to health, which we'll have to make in just a second. And basically, if I press quick attack, we will damage the health of this dummy. Now, obviously, we don't have the health, so we need to go ahead and find the health component. Now, you can see I've added the health component, but I'm going to go ahead and rename it to health so it matches this node right here. And now, if I hit play, you will see that nothing happens because I forgot to add our dummy to the scene. Let's go ahead and add our dummy to the scene. And now, let's actually press left click, and you'll notice that it works perfectly fine. That is our health, but there's obviously an issue, which is that it goes to negative zero. And you can even see that it goes to negative 60. It's basically going past that amount. You will also kind of think that we can probably go past the max amount of health, too. Right? Because if I'm able to go past the minimum health, essentially, then I can also go past the max health in here. Okay, let's say the dummy has five health and takes 10 damage. Do we want negative five health? Well, no. We want it to stop at zero. And we want to announce its death only once. Max will let us choose the larger of zero and the new health value. Min or minimum picks the smaller value, which is useful when healing up to a limit. Clamp handles both bounds together. We'll also check whether the dummy is already dead before processing more damage. For signals, we declare them, connect this the functions that should respond, and emit them when something happens. When the dummy calls queue free, Godot will schedule it and its children for deletion at the end of the frame. All right, so inside of this function or inside of this a script, I'll say, let's add three new signals. Now, signals are a new concept, but the basic idea here is we're creating our own signals that we can actually see inside of the signals tab. So, here you can now see damaged, died, and healed. These will basically trigger when I actually have these signals happen. But in order for them to trigger, I also need to emit them. Let's take a look at our damage function. The way we can emit this is by having the current health less equal to zero, then we can say died.emit. Now, we also want to change the functionality, I'll say, of this function just a little bit. Instead of just saying current health minus equals amount, we will say if the current health is less than or equal to zero, we'll just return. We'll also take our amount and make it equal to a max float between zero and amount. We'll get our current health and make it equal to essentially just current health minus the amount. And then we will say damaged.emit with the amount, with the current health, and max health. That is the function that we just made. Now, the heal function will also change just slightly. Very similarly, we're going to say if it's less or equal to than zero, then we'll return. And we'll emit the healed. Now, there's three other functions that we're actually going to need. First, we're going to want a function that sets the max health with the value and keep ratio. Basically, we'll have a ratio equal to one if the max health is less than or great equal to zero. Otherwise, it'll be equal to current health divided by the max health. The max health will be equal to the value and the current health will be equal to max health times ratio if the keep ratio. Otherwise, it'll be equal to the minimum float of the current health and max health. So, it'll take the minimum of these two. Essentially, what we're doing is we're just making sure that the max health stays at the same percentage or is the same absolute HP. We'll also have two other helper functions here called is alive and get ratio. This basically just returns true or false if our current health is above zero. We have 50 health left out of 100. How much of the bar should we draw? Well, half. Dividing current health by maximum health gives .5, which tells us that. Dividing the other way gives two, which doesn't represent the amount that we have left. So, we'll keep maximum health positive and let the health component keep the current value within its limit. Then, the HUD just uses that ratio to draw the bar. Um so, obviously we're not using it now, but we will kind of come back to it. Uh but just do understand what it does and know that we've added it for later. Okay, now back to the dummy. We want to go ahead and come here and connect our um signals that we just created. We'll do that by adding a function ready. Connect on died. Now, we're getting a error here. So, let's just double-check that the uh thing is correct. All right, so it we are not correct. It's actually called on health died. That actually makes a bit more sense, but either way we can connect it either through through or through uh the ready function. So, if you'd like to write it through code, uh uh this would be the way. Okay. Once we die, all we need to do is queue free. We'll just say queue free, meaning we'll destroy this object. object. I'm going to go ahead and disconnect this through here. But, now once it reaches zero, it should get deleted. And if I keep clicking, uh you can't really see that I'm clicking, but I am clicking. Um nothing's happening, and that's good. That means our problems are essentially fixed. Okay. Can we use the same health component on the player? Add it and connect died to a function that prints a message. Give yourself about 8 minutes. Test that damage reaching zero. That the message should appear once, and you can use the same component script that we put on the dummy. The player and the dummy should each have their own health values while reusing the same script. We still write a different response to died for each one. We can connect damage as well if you want to print the current value. Check those connections once so we don't accidentally run a response twice. We can change the dummy's health, but we want to use the sword touching it to cause that damage. So, now we need to connect those two things. So, let's go ahead and do that. So, who decides the sword hit something? Does the sword look for enemies, or does the enemy look for the sword? If both of them apply damage, one contact will count twice. Double the damage, double the shove, and every effect will play twice. So, only one side will check. The sword touches the enemy. First, we need the attack values. So, the sword's hit box holds damage and knockback. Then, the enemy's hurt box checks whether this contact should count. If it does, it passes the damage to the health component. So, our damage detection goes in one direction. The hit box still needs code for its attack data and hit history. But if but it doesn't separately apply the same overlap damage from another detector. We'll put hit box We'll put hit boxes in a group so the hurt box can recognize them in code. Now, a group is basically just a label. We still need the collision layers and mask to set up the overlap to be detected, though. You'll also see us pass self into a function. Self means this particular object. So, the other object can track of of which one contacted it. Our next step is to create a new script, create a hit box component. Going to go ahead and create. Going to open up the script and pop it up. The very first thing we want to do is create a class name hit box component. This will extend area 2D because this will be an area 2D node. Next, we'll add two variables, damage and knockback force. Those will be our very first two things we'll actually use. Next, we're also going to add a source node. This will be set pretty much when we actually add this node to whatever we want it to add be added to. It'll also be used for knockback direction and crediting kills. This is an incredibly important variable for later, but uh for now, all we also need to do is add to group hit box. Now, this is the entire hit box. There's no process, no signals. It listens to nothing. It's a label with a number on it. Next, we also need to make the hurt box, which we'll do by adding a new script called hurt box component. We'll go ahead and open that script up. And similarly, we will be a class name hurt box and we'll add a couple variables here. First, we'll also add a signal called hurt with the amount and source. We'll have a damage multiplier, a boolean that says invulnerable or not, uh a health which will extend off the health component which we just created, and a body node. To get started inside of this, we want to create a function ready. Here, we'll get the body.get_parent. Uh no, not dot equal. This will allow us to literally just go upwards and find our parent. Then, we'll also make sure we get the health of our player or body uh by saying body.get_node or null with health. Now, this is kind of important that we keep this in mind because now we have to make sure that every health is renamed to health. We'll also connect our signal here, area entered, which Of course, we'll need to actually create the function, otherwise we'll keep having that error. Inside of here, we will return twice if invulnerable is true or if hit box is not inside of the area. Next, we'll actually have the incoming damage by saying area.damage times the multiplier damage, which we will have up here. Then, we'll say if health.health damage incoming, then we'll basically damage the health with the incoming damage. Then, we will emit the hurt signal, which we have up here. Now, it's important that we actually adjust things. So, what we need to do is inside of the player controller, inside of the dash, right here, we want to say hurt box.invulnerable is equal to true. Obviously, we have the issue, which is that well, uh we are getting an error because we don't have hurt box. So, let's go ahead and add that at the very top. We'll say uh on ready variable hurt box is equal to component hurt box. But, of course, inner side of our player, we don't have the hurt box. So, we need to go ahead and add that. We'll add it here like so, give it a uh name called hurt box, and of course, we'll also need to add a collision shape. Now, this acts as an area 2D, so essentially we have the exact same thing of an area 2D, but it just has the uh script attached to it. Now, this guy, it's very important that we have the hurt box a little bigger than the actual uh collision shape of the player. Not super important, but it is a very nice have because when we're getting hit, it is very important that we have it fair, right? It's very important that the player is getting hit in a fair way. So, essentially, this is what is getting hit of the player. So, it's kind of up to you on how big you want this to be. Going back to our player script, we also need to set the invulnerability to false, which we will do inside of the and death. We will do that right here in the invulnerable. We'll also set the hurt box invulnerable equal to false. Okay, now to test this, um you can go ahead and pause if you'd like to try this yourself, but inside of the dummy, we're going to add the hurt box component. We're going to add a collision shape. Give it a collision shape of a capsule that is slightly bigger, that's fine. Now, we have this, but inside of our player, right next to the pivot weapon pivot, we want to add the hit box component and add the collision shape. And for this, I'm going to go ahead and add a rectangle. And this will quite literally follow the weapon. Now, I'm going to make it much larger than the weapon, and this is because when I actually smash my weapon or use my weapon, this thing will move, and you'd be surprised at how much bigger this needs to be to actually make it look like it's hitting. So, I'm going to make sure that it's a little bigger than the weapon. Um but if you want to experiment with this, very much go for it. Now, if we go ahead and hit play, we can notice that pretty much nothing happens, right? Eventually, it'll die, and that's because it what's its health got reduced to zero. Um because every time I entered my weapon, it got reduced, but visually, nothing was happening. So, that's a very big problem, right? We want things to actually visually happen. Now, there is another problem, which is incredibly difficult to show, um but I will kind of just mention, is that if this area, the hit box, enters our player's hurt box, which can happen, then I'm basically hitting myself. I'm killing my own player with my own weapon. Uh now, of course, that could be a mechanic that you'd like to do, but this would be what we refer to as a bug. Now, we can fix this very, very easily with layer settings. Essentially, team checks can work here as well, but here we use collision layers. Our hurt box only watches the enemy hit hit box layer, so our own sword never even gets detected. So, what we can do is go to project settings. We'll go to the layer name inside of the 2D render. All right, 2D physics is our important part. 2D physics is where we'll be doing at the rendering or the uh the layer assigning, essentially. For layer one, we're going to name this world. Layer two is going to be player body with layer three, enemy body. And I've gone ahead and just filled everything out. Um so, you can go ahead and pause the video and just copy this. But essentially, the important part is we're now layering or putting things on different layers. So, we have the player hurt box, enemy hurt box, player hit box, enemy hit box, or a projectile, and pickups. Now, what we can do is inside of our player, we go to our player hurt box and go to the collision. We want to set layer four and then mask seven, which is the enemy hit box. We'll go ahead and go to the hit box component. Go to the collision, and we want layer six, which is the player hit box. Now, we did this earlier, but now this makes a bit more sense. You'll see the player is on layer two, which is the player body. The mask is looking for the enemy body and the world. And this makes sense because we want to be able to collide with, well, the world and the walls. Inside of the dummy, we're going to go ahead to the hurt box and say we're going to do five here for the layer and six for the mask. What would we need to change so the dummy can damage us? Try giving it an enemy hit box. Use the enemy hit box layer from our collision table, then check the player's hurt box mask. Give yourself about 12 minutes for this. The dummy should hurt the player, while the player's own sword should not. Now, we don't have a hit box for the dummy, but I'm going to go ahead and add this for later, and this will allow us to actually test uh for the player to see if the player is getting hit. But, in the hit box for the monster for the dummy, I guess I suppose, we can actually go ahead and give him a sprite, too. Why not? And we'll give him him a little uh little sword that doesn't really move or anything. It'll just kind of sit there inside of the hit box. This one will be number seven for the layer. Cuz this is the enemy hit box that we're essentially hitting for the player. And now, if I hit play, I should be able to move up and down into this, and it's hard to really notice because nothing's happening, but if I go over here to our player, we will notice nothing because I realized I never added a health component to our player. Um and that's okay. Let's go ahead and see if we can reduce the health of our dummy. There we go. We killed our dummy. Uh this should pretty much work perfectly and reduce the bugs from our layering problem. One swing can overlap the same enemy more than once. If we apply damage every time, that enemy might take several hits from one attack, which sounds kind of cool, but it's not really fair to the gameplay. So, we'll keep an array of the hurt boxes we've already hit during the swing. Now, an array is a list. Now, append adds a target. Has checks whether it's already in that list, and clear will empty it. We need to clear it when the new swing starts. Otherwise, the target stays in there, and we can't hit it again. Each enemy should have its own hurt box. So, remembering one doesn't stop us from hitting another enemy during the same swing. Now, let's go ahead and go into our hit box component and we want to go ahead and add two things. A signal hit landed and a variable hit once per attack. We'll also add a array that hit this attack. This will essentially hold which ones or which targets got hit already by this attack. We'll add a function called reset hits. And then another function called try to register hit. So this will essentially take our hurt box and check if the hit box per attack is true and if it has this hurt box, then we'll simply return false. Otherwise, that means we can add this hurt box into our array. Once we do that, we can just append it and then emit hit landed and return true. Now inside of our hurt box, what we can do is inside of this function at the bottom we can go ahead and add if area has method try register hit, if not area.try_register_self, then return. What we'll do is actually move this below the check here because that actually makes a lot more sense to have all the returns together. Okay, we can hit an enemy and want to push it away, but that enemy already has movement of its own. If we just replace one velocity with the other, we can lose part of that movement. So we'll keep the knockback separate and add two together. Then we'll reduce that knockback towards zero over time. The starting force controls how strong the shove should be and decay controls how quickly it stops. Now before applying knockback, we'll check that body has that method first. That lets us use the this hurt box on objects that doesn't support knockback as well. For an enemy that should move, we'll still test that method is there and then the shove should happen. The attacker and target are in the exact same place. Which way is away from the attacker now? Subtracting their position will just give zero. So it doesn't really answer that question. What we can do is pick a random direction for this case. Random F gives us a fraction between zero and one. Multiplying that by tau t a u or tau gives us an angle around a full circle. We'll rotate a right-facing unit vector by that angle, then multiply it by the force. We'll choose a direction first and set this shove strength afterwards. Then, after at the very end here, we will add the knockback. We'll say, if body has method apply knockback, then we'll get the from and direction. So, here we're going to basically get the area's current global position, then the direction is going to be the body's global position minus the from, and we'll see to see we'll check to see if the direction.length is less than or equal to 0.01. If so, then that's basically means it's like zero, so we'll give it a default of right. Otherwise, we will apply the knockback with the direction.normalized the area knockback force. Now, on the receiving end inside of the player, we need to actually add that knockback. So, we'll go ahead and add these knockback variables, the decay, the knockback taken, and knockback itself. We'll also need a function at the very bottom, apply knockback. We'll have knockback equal direction.normalized * force * the knockback taken. Now, in order to actually make this work, you can probably imagine that we'll need to add this inside of the physics process. Now, before I go ahead and add this, you can probably guess or think, where can we add this? Well, we want to add it to the velocity. And we can add that right here. Basically saying, if or not if, but we're just going to take our velocity and say get move input * the speed plus the knockback. And the knockback will be equal to the knockback.move_towards zero with the knockback delay. Now, the the reason this works is because move_towards is essentially taking this number and moving it towards zero. And whenever I change the number knockback to a number that's not zero, then that means I'm going to get knocked back, which is done in this function. So, whenever I change that number, the knockback number, then our player gets knocked back. But before we move on, before I forget, we want to also add the health component. Let's go ahead and add the health, but remove the health. And now I should be able to check to see if my player's health went down. You can see that it did. We're at 90. Okay, you should be able to reuse the hit box and the hurt box scripts. Check the shape, attack values, layer, and mask, then confirm the damage reach the player's health component. If contact is detected, but health doesn't change, follow the accepted hit code as well. Correct collision settings don't replace the rest of that setup. Okay, our sword overlaps enemy A for three physics frames, and also touches enemy B during the same swing. We want one hit on each. Could we use one Boolean called already hit to handle that? Well, that would also block the first hit on B. We need to remember which targets this swing has hit. After hitting A, we skip A if it appears again, but B can still take damage. Then we clear the list for the next swing. Okay, the player gets shoved now, but the dummy doesn't. So, let's try giving the dummy some knockback as well. Copy the two knockback constants and the knockback variable from the player and add the same apply knockback function. Now, the dummy doesn't have any movement code of its own. So, it also needs a physics process that moves it by the knockback and shrinks that back towards zero. So, keep the player's number for now. Give yourself about 10 minutes to do this and check that a hit pushes the dummy away from the sword. Okay, here's the dummy script. The two constants, the knockback variable, and apply knockback are the same as the player's. The new part is physics process. The dummy doesn't read any input, so its velocity is just knockback. Every frame we shrink that towards zero with move forward, then call move and slide. With the player's numbers, the dummy only slides a few pixels. Now, that's fine for now. In the next lesson, we'll work out why it's so small. So, make sure that your dummy has this before you move on because the next lesson will start from there. Okay, the first swing looks pretty cool. But, what happens if we swing again or stay inside the dummy? Let's check that before adding more attacks. Okay, the game runs, but the dummy only takes damage from the first swing. So, where do we look? Well, start with the running dummy in a remote tree, rather than the saved scene. We can add a breakpoint where the hit is checked and look at the values when the game stops there. If the target is still in the previous swing's hit list, then we need to check where that list gets cleared. Also, let's remove our temporary click to damage test. Otherwise, a mouse click can still reduce health without the sword touching anything. We want to test the actual attack now. As of right now, if I use my sword to try and kill the dummy, we'll notice if I go to the remote section on the top left, click the health inside the dummy, you might have noticed that the health only went down once, from 100 to 90. But, as I do this again, it's not really working. You see, it went down one more time, but this should be happening relatively consistently consistently, but it's not, which is a big problem. Another issue is that it pretty much barely twitches. It does get knocked back, but it's barely visible. And of course, another issue is if I click, the health of the dummy is going down. This isn't me hitting it with the sword, it's just me clicking, which is a bug. We don't want that in the game. Now, the first one, which is super easy to fix, is inside our dummy script over here, we can pop this out and see this function right here. This was what was causing our health to go down. We can go ahead and just delete this entire function because it was meant to just help us see if that actually worked. Another thing we'll add over here inside of the area entered is a print function to see which area enters the area for our hurt box. Next, inside of the hit box component, I'm going to go ahead and add a break point right here on this line, on line 20. A cool trick to do this is also if you hover this line and hit F9, it will add a break point. If you're not able to find this little break point button over here. Now, if I hit play, you'll see that the break point triggers. And you'll notice that it's empty. Now, if I click F12 or this button right here, continue, this allows us to actually go to the next line inside of the code. And we'll see over here, hit this attack. We now have this object. This is the hurt component. Now, if I do it again, you'll notice that again, it still has this size, which is a bug. This should have been empty. The dummy's hurt box is sitting inside of it. So, we need to fix this. If we hit control shift F and hit in reset hits, we will find the function reset hits. But you'll notice that there's nothing that ever calls this function. We're never actually resetting the hits. So, that is our problem. So, to fix this, we're going to go ahead and go to the player, stop the game first. Inside of the script at the very top, we're going to add a hit box on ready variable. And then, inside of our physics process, we'll go ahead and add an input is action just pressed quick attack, hit box reset hits. Now, before we actually continue, let's go ahead and go to our hitbox, untick this break, hit play, and we'll see in the inspector over here, we have the array size one. Now, if I go to my player, inside my hitbox, you'll see it says array size zero. Okay, the dummy's sword has the same problem. It's hitbox remembers us after the first hit, but the dummy never swings. So, nothing ever clears that list, and it can only ever hurt us for once. For now, we'll untick hit once per attack on the dummy's hitbox, so it can hurt us every time we walk into it. Now, we want to go ahead and go to the dummy inside of the hitbox component, we're going to untick the hit once per attack. Now, if I hit play, and I hit him, and then left click to reset, you'll see that it works fine. Our health is getting reduced. This is the health of the dummy. Now, let's say that we give the dummy the player's knockback setting, run it, and it barely moves. Godot isn't really showing an error here. So, technically we should be good, right? Well, before changing numbers, we want to find the first place where what happened isn't what we expected. Is the knockback function even running? A print might say yes every hit. Is it getting the right values? Well, a breakpoint will let us stop there and look. Right direction, force of 200, exactly what we set. Okay, so it ran with the right numbers, too, and we could barely see it move. Okay, well, how far should those numbers actually move it? Before we change anything else, let's work that out. Basically, if something starts at some speed and brakes at a steady rate, it travels about that speed squared divided by twice the braking. The dummy was only keeping part of that push, so it started at 120, brake at 1,700, so that's about four pixels. That's basically why we didn't see anything. So, the code can be doing exactly what we asked, and that's exactly what it's doing. And the shove is just too small to actually see. So, the dummy takes the full push and breaks more gently. 200 breaking at 900 is about 22 pics. It's a little more. Now, this tells us something very useful. If you double the push, it goes four times as far, having the brakes twice as far. And since the push is set per weapon, there'll be a lot of weapons tune the breaking first. Now, the knockback is also kind of still a problem. To fix this, we'll go ahead and go to the knockback decay, and we'll go ahead and change this to 900 and the knockback taken to 1.0. This is basically just fine-tuning what we actually like to see inside of our game. If dashing makes us invulnerable, that should probably be one flag that the hurtbox reads. If the player keeps its own copy as well, then the two should agree right up until something sets up one or not the other. Then, we get hit mid-dash and there's no error. Now, another problem is inside our player controller, we want to go ahead and actually delete the invulnerable. This is basically just a duplicate now at this point. If we go ahead and control-F, we can find the invulnerable parts and just delete these because now we have the hurtbox invulnerability. That's the part that actually matters. The old invulnerable was mainly for the hazard. But now, in here, obviously, this won't work. So, instead, what we'll do is get it to actually check the hurtbox is invulnerability because that's where the invulnerable variable lies, inside of our body's hurtbox. Let's go ahead and close that. And now, if I click play, you can see that I can pretty much knock our little guy back. Now, this might seem a little odd to you in terms of, oh, I have to click to reset our attack, but at the moment, this actually works pretty nicely because in our next couple parts, we'll be adding a swing to our attack. And the cool part about this is that we don't actually want our sword or weapon to be doing damage if I'm just swinging it around like this. At least not in our game. The reason we want it to work like this is because in a minute we'll add a swing to our click and when I actually click, that's when the reset happens. Not only that, but that's when the damage happens as well. Okay, let's follow one hit through what we've built so far. The sword's hit box carries the damage and the knockback. When it enters the dummy's hit hurt box, the hurt box asks asks the hit box whether this swing has already hit it. If it hasn't, the hit box adds that hurt box to its list. And then and the health component takes the damage. The list only empties when a new swing starts, which is why the dummy stopped taking hits until we cleared it on each click. And when the shove looked too small, nothing was broken. The numbers were just too small. So, we worked out the distance instead of just guessing. The knockback number looks big, but how far does the dummy actually move? That's the real question. Measure on hit, then try tuning it to roughly one tile, around 14 to 20 pixels for this test. Save the starting position when the hit arrives and measure when the knockback reaches zero. Give yourself about 8 minutes with no wall or other movement affecting the test. Okay, compare that measured distance with the estimate from the initial speed and braking. Physics steps and collisions can affect the results, so don't expect exact equality here. If the difference is large, check whether another function changes the velocity during the shove. Then tune one value at a time and repeat the same test. Okay, now we can trust that hit detection. Next, we need to decide which part of the swing we're actually allowed to hit. But how does the game even know what part of the swing that we're in? Well, we could keep a bull a boolean says that we're attacking. But it does that mean that we're winding up dealing damage or recovering? Because there's different parts to the attack. Those will also need different behavior. And if we add a boolean for each one, now we have to stop combinations that shouldn't happen. Okay, we're idle so we can start an attack. Then wind up prepares it. Does that deal damage yet? No, that just start an active when we enable the hit box. Now afterwards recovery stops us immediately starting another swing. The quick attack can enter active without the heavy attacks wind up. The weapon profiles also change damage, reach and timing. So we'll compare the actual phase durations as well as the damage values when testing how the attack feels. Okay, let's say we store a number for what the sword is doing. Zero means idle, one means wind up and so forth. Okay, but a week later we see a check for state equals two. What was two again? Well, we shouldn't have to remember that every time I read code. That can obviously get really annoying. An enum give those numbers actual names. That's basically all it is. We'll call it in state and add names like idle and active. But each of these have their own respective number. Then we can set the current state to one of them and check it later. These are named integer values, not separate true or false flags. We still write the code that changes the state and we'll only enable damage while the attack is active. All right, the very first thing we want to do is create our weapon pivot script. Go ahead and create a weapon controller. Inside of the weapon controller, we'll go ahead and open it up. The first thing we want to do is simply add a class named weapon controller and we'll add a few variables. The first thing we're going to add is an enum state. It can only be one of these things at a time. We'll add three variables on ready, weapon sprite, hit box and hit shape. These will come in just a second. We'll actually need to create our scene because obviously we're getting stuff that doesn't exist just yet. Before we do that, we'll continue adding our variable state. This will allow us to keep track of what our current state is, and we'll start by having the idle. We'll have a state timer, cool down, current is heavy, and player. We'll start off by adding our function ready. This will allow our player to get assigned to our get parent. We'll disable the hit box, which is a function that we'll create, and then we'll have a attack hit box. Source node is equal to player. We only want the sword to hit during the active part of its swing. So, which setting do we turn on? Monitoring sounds right, but that lets an area look for other objects. Monitorable lets other areas find this one. The hurt box checks for our hit box. So, we need to change the hit box monitorable setting. What we need to do before we continue is add our disable hit box. Now, following this, the obvious opposite to this is enable hit box. We'll essentially need to just make sure the monitoring and disabled is true for the monitorable and the disabled is false for enabling it because disabled means that it's disabled. So, we want the opposite of that, which is false. And then the disabled will make it true, whereas monitorable will make this false. Okay, we know which state we're in, but the wind up needs different code from the actual hit. How do we choose which one runs? Well, match compares our current state with each branch and runs the one that matches. If we're in wind up, we count down until it's time to enter active. Active finishes and moves into recovery. Then recovery brings us back to idle. That's the state machine that we're going to be building here. The timer will just count down. We decide which state comes next when it ends. You'll also see pass in functions we haven't actually filled in yet. That means do nothing here for now. The function can exist, but its behavior still needs to be added. The very last thing we want to do is add our process function. We'll start off by just adding in the cool down. If it's greater than zero, we'll subtract all the way to delta or subtract minus equal delta. And then, the important part is to match the state. We're going to match our state with wind up, active, and recovery. For the state well, timer, we'll subtract uh minus equals delta for all of them. And then, of course, we'll match whichever thing we want. So, if the state timer is less than or equal to than zero for all of them, we'll do the respective thing. For the wind up, we'll begin active. For the active, we'll begin recovery. This is basically starting the next thing. In recovery, we'll start the idle or set the state to idle if the timer is less than or equal to zero. This match is the entire engine. This is what runs the weapon controller. Now, before we continue, we have an obvious problem here is that we haven't built the scene for this. So, let's go ahead and close this. And all we actually need to do is just add our weapon controller to the weapon pivot node. Now, you'll notice that we actually extend node 2D. And that's why we did that at the very top. So, that actually makes a lot of sense because the weapon pivot needs to have a position 2D. And now, these make sense because now we have a hit box and everything. But we need to rename everything. So, the weapon sprite, we'll rename this to weapon sprite. The attack hit box, we'll rename this to attack hit box. And the collision shape 2D, we can just keep it collision shape 2D. But the rest of the code will now make sense because here we set the player to get parent, which is the parent of the weapon pivot. Let's head back into the script at the very bottom and continue the the functions that we need. The very first function we'll add is not the begin active, but try quick attack. This will allow us to actually try to do a quick attack before anything else. First, we'll check to see if the state is not equal to idle or if the cool down is greater than zero. If so, we'll return. Then, we'll set current is heavy to false and cool down equal to 0.35. This allows us to just control the cool down for whatever attack we're doing. Now, similarly, we're going to do the almost same thing, but we're going to try heavy attack. So, it's almost the exact same thing, but current is heavy will be true. The cool down will be a longer, so 0.9. Now, keep in mind, this is literally just as long as you want it to be. So, the quick attack is how long do you want the player to be able to spam? For the state, we'll get this to wind up because for the heavy attack, we want to wind up first for a heavy attack. And that basically brings us back to this state. That is why we're going to have this wind up that kind of winds up the attack, and then we begin the active, we begin the attack once we actually finish winding up. Now, the important part is the begin active. Let's go ahead and add this function to stop all our errors from before. We can just go ahead and hit pass just so we can actually get rid of our errors. We'll also add the begin recovery function at the bottom and it just hit pass so we no longer have any errors. Okay, we've done quite a bit, but now at this point, we should have no errors whatsoever. For the begin active, we want to go ahead and first set our state to active. Then, we'll set our state timer equal to point 16 if the current is heavy. Otherwise, we'll set it to point one. This basically allows us to have different state timers depending on what we're doing, if we're doing a light attack or heavy attack. And the current is heavy allows us to actually keep track of well, which attack we're actually doing. Okay, let's say we want to make that this hit box wider. Okay, what shape do we give it? A rectangle has a size that we can change, but a circle has a radius. The code needs to know which one it's actually looking at because obviously these are two very different shapes. So, before setting size, we'll cast the shape to rectangle shape 2D and make sure that's the resource we assigned. The cast doesn't convert a circle to into a rectangle. There's also something to watch when copying two scenes. Two collision nodes can reference the same shape resource. Changing its size will affect both. If we need them to have different sizes, they need to have separate shape resources. Next up, we're going to create two variables, a size and an offset. The size will be a 64 by 43 or 48, sorry, if it is heavy, otherwise it'll be uh 46 by 32. And basically, what we're going to be doing is taking our hitbox shape, which is our hitbox, it's literally our collision shape at the top, and we're going to adjust its shape, its size depending on the size that we just created. So, depending on if I'm doing a heavy attack or not, I'm just basically increasing the size of my actual hitbox. Now, this is quite neat because I get to control what I actually use. So, here we're going to be using a rectangle shape 2D. But furthermore, we're going to also adjust the damage. We're going to take our hitbox damage and set it to 45 if it's heavy, otherwise it'll be 20. So, we're basically doing almost a little Oh, not almost, a little bit more than double if we're doing a heavy attack. And then similarly, for the knockback force, we want a bigger knockback force if it is heavy, otherwise it'll be 170. And then we'll take our hitbox and reset the hit. Now, you can now imagine our previous bug of resetting the hit when we actually attacked our thing, this is where it happens. So, in the previous part where we kind of quote fixed our bug of the reset hits, well, this is our new bug fixer. And the final part that we'll actually need is to enable the hitbox because this is where we will actually enable the hitbox to be able to hit something. The last part is begin recovery. Now, this is also important because we basically want to disable our hit box, and then we want to set our state into recovery. Then we'll set our state timer to 0.2. This basically sends us back into the recovery part over here, and after 0.2 seconds, we'll be able to go back to idle. Once we're back in idle, then of course I can begin attacking again. Okay, but now we actually want to set up the attacks. We need need to go back to our player controller. And at the very bottom, we'll go ahead and add handle attack input. We have the weapon try quick quick attack and try heavy attack. Now, this is cool, but obviously we don't have the weapon. So, why don't we go ahead and go to the top, go under the on ready over here, and add our weapon controller with the weapon pivot. I also realized we also have the weapon pivot over here, which we do use over here. So, let's actually reduce the amount of duplicates that we have, replace this with the weapon, and get rid of the weapon pivot over here. And there we go. Let's go ahead and save. Now, there's an obvious problem before we move on. Um maybe two obvious problems is we have this quick attack thing that we're doing down here, but they're like it kind of doesn't make sense, right? Well, why are we doing that? And we're also resetting it when I can just replace all of this with handle attack input. All right, let's go ahead and give it a try. Okay, one of the first problems that we probably have is invalid type. Um we are probably doing something with the weapon sprite. Most likely, yeah, over here we have the weapon sprite, which we uh don't have it called sprite anymore. It is now called weapon sprite. So, let's go ahead and fix that, close, and give it a try again. There we go. There we go. Now I have an attack. That's awesome. So, we can even try the heavy attack. You can see when I right-click, it kind of winds up almost like there's that little delay, and then it knocks it back quite a bit. That is the heavy attack happening. We can even see on the bottom our old entered attack hit box. That is our player's hit box. Now, there are a couple complications with this. One of the problems comes with running and attacking at the same time. We can swing the sword and run at the felt at the same time where basically attacking just costs nothing. Now, in the areas part, we also might notice that here the hit box component is giving us an error, and that's because uh it got renamed as well. So, we want to go ahead and change that's name as well. Let's say a physics contact triggers a state change, and that state change turns our hit box off. Godot can still be working through the contacts at this point. So, changing the areas detection settings right then can cause an error. We'll defer that change, which means asking Godot to apply it once it's actually safe. The enemy attacks will still need the same approach. We'll also change movement during the attack phases. Slowing the heavy wind up means starting it can leave us in range longer. Does that make us think about when to use it, or does it just make it feel like we're stuck? We'll try the attack in a fight and decide how much slow down that we actually want. Okay. Now, before we uh kind of change anything, let's go ahead and head over to our weapon controller. Now, we want to basically replace our enable hit box and disable hit box with a better version of this. What this will look like is instead of doing monitorable and disabled equal to something, we're just going to do set deferred. This almost queues up our thing. So, it basically fixes our previous problem. We'll do the same thing with disabled hit box, and that's it. Now, monitorable can see others Can other areas see me? Not monitoring, which is whether I look for others. The hit box is passive, just remember that. It never looks, it only needs to be seeable. Okay, now the part that get kind of fixes our movement, uh where moving and attacking is kind of free. What we'll do is add a function called get move factor. This will basically tell us match the state. If we're in the windup, return this number. If we're in the active, return this number. If heavy, otherwise we'll return this. If recovery, return this. If by default we're in none of these, we'll return one. We'll also create a function called is busy, and that will just say return state not equal to idle. This is a boolean, true or false. If we're not in the idle, it'll return true. If we are, then it'll return false. All right, now in the velocity line, we want to go ahead and replace this by adding the weapon. dot get move factor. And we'll go ahead and get that to match, so we get rid of that error. And then, but make sure we add the knockback at the very end. So, everything here needs to multiply against each other, plus knockback in the end. Okay, now imagine we add a spear. Do we need to write the whole attack system again? Well, it still winds up, attacks, and recovers. We mainly need to have different damage, different reach, and different timing, and maybe a different animation. So, we'll put those settings in a dictionary for each weapon. A dictionary pairs a key, like damage, with a value that we can look up. We'll keep the weapon profiles in an array and use an index to select one. A constant gives us a named value we don't reassign. To switch weapons, we increase the index and use the remainder operator to wrap it back to zero after the last entry. That needs a non-empty list, otherwise there's nothing to select or divide by. Now, going back to weapon controller, we now want to basically add types. Now, different types of weapons will be done like that like so. We'll create a constant sword, spear, and dagger. Now, what we'll do is we're going to go ahead and This might seem like a lot, but what we're going to have here is basically different profiles for our weapons. We're going to have a corrupted cleaver with damage 20, corrupted knockback 170, active 0.10, cool down 35, and so forth. Now, this seems like a lot, but this will come into play a lot more usefully later. We'll also go ahead and add two other variables, available weapons and slots. Now, I'm going to go ahead and zoom out here. If you want to go ahead and pause and and copy this. But of course, um just kind of keep in mind, I do have a lot of this on my website, so if you guys want to be able to either download the projects or be able to follow along through text on the website, go for it. Um that I do very much encourage it. But let's continue. Now, we also will want two other functions. We'll want to create a profile, which basically just returns the available weapons with our slot. We'll also have a swap function with available weapons.size if it's less than two or if the state is not equal to idle, then we'll return. Otherwise, we can just say slot is equal to plus one divided uh percent, which basically is the remainder of available weapons.size. Now, to actually make this work, we want to go down to the quick attack and we're going to replace a couple things here because we have basically added some things that matter. One of the things that matter is the cool down. We'll replace this with a float profile times a CD mult multiply. Now, we'll have an error here for a bit because we don't have that function just yet. In the heavy attack, we'll go ahead and replace this with a similar thing, but we'll also have the state timer. For the begin active, we need to replace a lot of these things too because things like damage are being replaced. However, we'll have a couple things that we're calling that don't exist just yet like compute damage and CD mult. This is super simple. We'll just head to the bottom and add CD mult. This basically would just return one for now. This is kind of important because we will edit this later. We'll also have compute damage, which will basically get our profile and return the H damage if it is heavy, otherwise we'll return the Q damage. Now, two functions that currently just return the value which is given and it looks pointless in direction now, but it's the same move as the component health health component in the last lesson. One place damage is decided. When chapter five adds bonus damage, corruption multipliers, and berserker bonus and things like that, things like these will come into play a lot better. You'll notice that having good practice in code when we write things like this will actually matter quite a bit. Okay, now we want to actually use the swap weapon or make the swap weapon work. So, let's go ahead and head over to our player controller, go to the handle input attack and on the top, we'll just do the exact same thing. We'll swap weapon and if so, then we'll say weapon.swap. All we need to do is just make sure we have this in the input for swap weapon. So, here you can see we have Q. And you'll see if I press Q, my slot over here will change from zero to one. That's because those are my available weapons. I have zero and one. Now, obviously there's no visual change. What if we make the windup longer, but leave active time and recovery alone? Well, which part of the attack should feel slower and when should the sword still be able to hit? Okay, take a couple minutes to try it, but decide what you expect before actually pressing play. We wait longer before the attack starts, but it can still deal damage for the same amount of time. The hit box should stay disabled during windup and recovery. If it hits during the warning, check where we enable it when changing states. Can you make another weapon using the profile fields that we already have? Try something with a different reach and different timing, like a short fast attack or a slow longer one, like a spear, for example. Give yourself about 10 minutes to try this. Swap to it and check to see if that you can describe how you position and or time the attack differently. Changing damage can affect how many hits that we need. While reach changes where we stand and timing changes when we can attack safely. Compare those separately. If the new weapon feels identical, then check whether the profile values are actually copied into the attack, then try a bigger difference in one field before adjusting the others. Testing this yourself is pretty much one of the best ways to actually go about this. Okay, so now the damage works. But, the thing is, if we weren't watching the number, how would we know if I got hit or if we hit the dummy? Now, an easy fix here is just to give better art, a cooler sword, and a better sprite, but does that really fix anything? A better sprite still doesn't really tell us that we connected that hit. Doesn't give us that feeling that I hit something. We need something to happen when that sword connects. Maybe the dummy flashes, maybe it gets pushed back a little bit. That's the feedback that we're going to add, and it needs to start when we actually hit something. So, for example, when you're playing Minecraft and a creeper blows up behind you, you know very well that the creeper is about to hit you before it even hits you, and you know when it exploded for a lot of reasons. So, we're going to explore why that is and how to do it ourselves. One hit can start a flash, particles, and a damage number together, but do they all need to end together? Well, no. We can give each one its own duration. The flash might be very short, the particles may last a bit longer, and the damage number moves away a little after that. We'll connect them to the same accepted hit event and choose a duration for each one. Then we can turn them off one at a time and compare the result instead of assuming more effects always improve it. Okay, the player gets hit. So, we want camera shake. An enemy gets hit and maybe we want it there, too. Now, the question is does every enemy need its own code to find the camera? We could do that, but we'd keep repeating the same setup. So, instead we'll keep a game manager available as an auto load. Godot creates it when the project starts and keeps it when we change scenes. It's basically a global thing that we can always access. Our camera can register itself with the manager and the enemies can just ask the manager for that shake. Class name gives a type a name. The auto load is more like an object that's already running. We still need to update its references when the player and camera changes, though. The very first thing we're going to do is create a new script here called game_manager.gd. We'll go ahead and create a template with the node and hit create. Now, to actually make this script auto load or become global, we need to go to project settings on the top left. Go to globals. If you're using an earlier version of Godot, it might be called auto load on the top. All we need to do is select a script/scene. Find your script over here in game_manager.gd and go ahead and just open it. The cool part about this, I want to kind of just hint at something, is you're also able to auto load a scene. You can also disable and enable the global variables on the right. Once we've gone ahead and done that, we can actually test this by hitting play and heading over to the remote section on the top left and that shows our game manager on the top over here. Any variables or any functions that I put will now be accessible here and it's now accessible globally. Let's go ahead and create this or open up this script. And the first thing we'll do is add our camera. Now, obviously our camera isn't accessible at the moment, so we're going to have to register that in just a minute. Okay, so for hit stop, we'll briefly stop the game time and then restore it. But if the timer uses that same stopped clock, how does it ever finish? We'll make it ignore time scale so it can keep counting in real time. A wait pauses this function until the timeout signal arrives. Other code can still run though. Now, another hit could start before that first wait finishes. So, we'll give each request an increasing number and check it after the wait. If it's an old request, it returns without restoring the time scale. That way, the first hit doesn't cut the second hit's pause short. So, that way we just basically don't get weird interactions. But before we do that, we'll also add our hit stop token. We'll go ahead and replace these functions with register camera. This will basically allow us to give camera access to this manager. Next up, we want to go ahead and add a shake camera where we already have, but all we need to do is get our camera and say add drama. Now, we have a couple checks here. We're basically checking if the camera is exists, if it's not null, and if we have the method add drama. This is very useful because sometimes I might misspell something or something just might not be the same, right? What if I said add shake, right? That doesn't exist. So, this kind of allows us to get through the game without erroring. Next up, we'll add a hit stop function. This is literally what it sounds like. It's a hit stop. We're going to stop at the engine the moment we actually hit something. The way this works is we actually adjust the engine time scale. This allows us to take our time scale and set it to zero, literally stopping the entire engine. This simulates as if I just stopped everything inside the game. This way we are able to control everything through this rather than stopping everything manually. Next, we want to re-enable it, which we'll do by taking the my token equal to hit stop token. We'll get a timer. We'll create a timer with the duration, which is given over here, will have true, false, and true. If I go ahead and left-click this, you can see what these pertain to. This will be process always, which we want true, process in physics, which we don't want to be true, and then ignore time scale, which we uh want to be true. The reason we want it to ignore time, which I think makes sense, is be well, because if we stop the engine, but we also stop this timer, then how are we going to find out if the timer is done? Um and that's basically it. So, here we can get the await timer.timeout. This allows us to wait for the timeout function being called or signal being called inside of our timer, uh which is not in there, but uh basically the timer has a signal called timeout, and we're going to wait until that signal gets triggered. Once it does, we'll check to see if my token is equal to hit stop. If so, then we will say engine.timescale back equal to one. This is just the default value. Um if you want to change this, then go for it. Some games actually do allow you to speed up the engine, right? This is basically just like the time of the game. So, if you want to do double time, then that's your default. Okay, our sword can now prepare a swing, deal damage, and recover. Those need different behavior. So, we gave the state names with an enum and used match to choose the code for the current ones. The timer ending doesn't decide the next state by itself, though. We wrote that transition. A different weapon can use the same sequence with different reach, damage, and timing. Then we added hit stop through in the shared manager. But if we stop the game time, how does the wait finish? It needs a clock that still runs. Before we add more effects, check when the sword can hit and when we can attack again. The feedback needs to follow those actual events. We want an enemy to flash when we hit it. We could make another image, but then what about every animation frame and every other enemy? We can change how the existing image is drawn instead. That's where the shader comes in. The fragment function calculates the pixel color. UV tells it where to read the texture and alpha tells it how transparent that sample is. For an outline, we also check nearby samples around the sprite's edge. For a flash, we can mix the normal color towards the flash color. Uniform are values we can set from our game code like how strong the flash should be. The shader changes the image. Damage is still handled by the health code though. We'll go ahead and close this function and we're going to create a our first shader. Before we go ahead and create our shader, we want to create a new folder for these shaders. Click okay and we're going to call this shader. We're going to create a resource over here and add a shader. There is also visual shader, but we'll be using a regular shader. We'll call it sprite_fx and then .gd shader is the auto complete. Go ahead and create and our script will pop up on the bottom here. And the very first thing we want to do is make sure the shader type is a canvas item. We're going to add a couple of variables that we'll actually need here. So, uniform float flash amount. This is the amount we're going to flash, color, the outline width, outline color, and outline pulse. You can see the numbers here. I'll try to zoom this out so everyone can see. And there we go. These are the variables we'll need. Next up, we're not going to need the vertex for now. So, we're going to go ahead and delete that. We're going to need the fragment. So, let's call We're going to take our color texture with the texture and UV. This basically gives us the texture of the well, canvas item that we're using. So, this will bit make a bit more sense once we actually use it, but essentially taking the sprite texture. Next, we'll check to see if the outline width is greater than zero. Now, the fun part about this is that we're basically writing in a different language. So, we do need these colons here. Otherwise, it won't work. Next, we will take the uh pixel px get the texture pixel size times the out width width outline width, which we created earlier, and get a equal to zero. Now, we're going to be changing A in quite a few lines here. I'm not going to go line by line, but the basic idea here is we're going to be taking our texture and adjusting it with the UV. Lastly, we'll create pulse and a call. And now, the very last part that is very important is to actually flash towards the color, which we'll do by saying l.rgb is equal to mix with the call of RGB with the flash color and the flash amount. We'll also adjust our color by equaling making it equal to call. That is the part that actually matters and, you know, applies our shader. Okay. Now, we've got a flash. Now, the player needs it. The dummy needs it, and our enemy need it, too. We can put this setup in one helper called juice. We don't need a separate juice object every time, so we'll just make the function static and call it through the class. It can still create a material and change the sprite we pass it in. Each sprite needs its own material if we want its flash to change independently. They can share the shader itself, though. Dot new creates the material object, and we can assign it to the sprite. Preload loads a known resource with the script. Whereas, load gets it with that line run. Res path start in the project folder. Our helper extends ref count, so the instance would be released when nothing keeps a reference to it. Once we've gone ahead and done this, we want now want to create our script that will apply this shader. So, we'll go ahead and create a new script in the scripts called juice.gd. Once we've done that, we want to go ahead and open up the script, and I'm going to pop it out here. And we're going to make this script class name juice with extend rough ref counted. Now, the important part here is to make sure that we actually load our fader. And make sure that the path is the same for you. So, if you want to double-check, you can uh right-click this and copy path or absolute path. If you do that, should give you the path. Once we've done that, we're going to go ahead and make a static function. And what we're going to do is basically make our shader work. So, the way this works is we're creating the shader as an object, getting the shader equal to the shader sprite or sprite shader. We're basically loading it in to the material.shader. And then we adjust these three parameters, which we added in our shader earlier. And we're going to return the material. We set the flash to one and enemy lights up. Cool. But now, how does it fade back? Setting it straight to zero would just switch it off. Between lets us move that value back and forth over a short amount of time. It can change a property directly or call a function with each new value. Here, we use a small inline function called lambda to pass that value into the shader parameter. We'll create the tween from the sprite, so it's tied to that node. If the sprite is freed, its bound tween stops, too. We can use that same approach for the damage numbers and weapon animation later. Next up, we're going to create a function called a static function flash, where we're passed through the sprite, color, and duration. We'll first return uh true if the sprite is equal to null. And then we want to get access to the material. So, this basically gives us access to the flash material. And if it's null, then we'll just return. And then you'll notice here that we actually set these to zero. So, we want to set the things to our uh proper numbers and color over here. So, because it's zero, we want to make sure we actually set it to something that we can use. And lastly, we'll create a tween by saying tween or TW for short equal to sprite.create_tween. This basically allows us to create the tween inside the sprite. It doesn't really matter where you put it. Uh it just is nice to keep uh track of where it is. Then we'll take our method and create a function inside and basically have our material dot set shader parameter to V with 1.0, 0, and duration. Once we've done that, that is it because this function returns void, so we don't need to return anything. Every hit can create a little particle burst, but if we keep adding those nodes over and over and never removing them, what's left after 100 hits? 100 old effects. So, we'll make each uh burst emit once, then free it once it finishes. Amount sets the particle count, and lifetime uh sets how long each particle will last. Explosiveness changes how close together they they're emitted. At one, they come out together as a burst. So, it doesn't increase their movement speed. That's the velocity setting. Spread changes the direction that they can travel in. We'll adjust those separately so we can see what each one does when we change it. Next up, we will create another function for impact. This will have our world position, color, amount, and scale. We have defaults for all of these, but that's the basic idea. Once we've done that, we want to go ahead and create our CPU particles. The idea here is we're going to be creating a CPU particle effect inside of code rather than using a actual scene. So, I'll show you what this might look like uh inside of Godot as a scene in just a second, but let's complete the code here. So, once we've gone ahead and created our CPU particles, we want to set emitting equal to true, one shot equal to true because this is an impact, so this only happens once. It's like one big pop, and that's it. We'll also set the amount equal to the amount over here. This is basically like 10 particles, the lifetime to 0.35, and explosiveness equal to one. Now, what this does is literally have almost like an explosion from the middle, and it is from 0 to one, I believe. And the basically the higher it is, the more explosive it is. The lower it is, it's almost like it doesn't explode at all at zero. Once we've done that, we want to make the direction equal to zero. And this is kind of important because this is an explosion, so it's kind of like 180, which we actually do over here and spread, setting it to 180. This spreads it over 360. So, it's basically double the amount of what the spread is. And then the fun part is the velocity, which actually set like cells that impact. We'll also have the max, so minimum max, basically setting it to 60 and 160 times the scale. The scale amount of the actual particles. Now, this basically just depends on how big the game is, and these are tend to be the numbers that seem to work for me and for this game. And once we're finally done that, we want to go ahead and set the global position and then add it to the world. We'll add it world world.add_child to P, P being the particle that we just created, and then we will say finish.connect queue_free. Basically meaning once it's finished, once this particle is finished, it'll queue_free. And this is very important because we don't want to leave this new object that we just created inside of our world because then we'll be stacking all these particles inside of our world, and we'll have a billion particles by the end of a run, which we don't want. Okay, next up is squash. We make a sprite a bit wider and shorter for a moment. Then let it spring back to its normal size. We'll use it on the sword when a swing starts. So, the sword has a bit more punch. The helper does it with a tween. We give it to the node, the scale to go back up, how much to squash, and how long it takes. Set trans picks the shape of that movement. And elastic overshoots a little and wobbles before it settles, kind of like a spring. Next up, we'll create a squash effect. This basically just literally allows us to have a squash on our whatever we want. This one is a lot simpler. We'll basically just create a tween by saying node.create_tween wherever we call this. And we're just going to tween its scale. And so, we'll do this by getting the tween.property function, taking our node, its scale's property, and then we'll take its base scale, and then we'll set it uh to a We'll do this over a duration. So, we're taking its current scale and setting it or tweening it to the base scale. So, that's the idea. Okay, once we've done that, there's a lot of code, but we're not done yet. We want to head over to the hurt box component. At the very top, we're going to add a couple new variables. We're going to export flash color, impact color, and show damage numbers. Now, this is cool because I'm going to export two different color variables, and I'm also going to have a variable sprite. But, the cool part about this is if I close that and head over to a hurt box, you will see the flash color and impact color. So, this allows to change this depending on what you want. If you click it, you can see I can change it around, but I'm going to not going to change it. I think white is a pretty good impact color or flash color. Okay, once we've done that, inside of the ready function for our hurt box, we want to go ahead and add sprite equal to body.get_node_or_null Sprite2D. This just needs to be the same as this, which is not the same. So, I'm actually going to go ahead and rename our tile to Sprite2D. The body of our thing needs to be the same. And this is kind of important over here for dummy two, we need to make sure it's called Sprite2D. One important note is we need to make sure this comes after the body because obviously I'm saying body.get_node, and if body is not the parent yet, then this won't work. Once we've done that, we're going to say if sprite and sprite material uh we're going to check if it's equal to null or not, basically. Basically seeing if everything is valid. If so, we will set our sprite material equal to a juice. make_flash_material. Juice is literally just calling this uh script that we just created. We can do that because this is a class name. Now, we also want to uh add our flash when we actually take damage. So, we'll add that right here after the health.damage, which makes sense because once I damage our thing, we want to flash it. We also want to impact it. Now, another thing, I'm just going to say we should probably delete these print functions. Um if you have any other print functions in your game, go ahead and delete them now. But, yeah, this is basically implementing what we just made, the flash and impact uh variable or function, I believe. All right, once we finish that, that is our visual effects happening. Now, one thing that will do now is add our audio. When a hit happens, we want to ask for the hit sound. We don't want to type its whole file path though every time. So, we'll connect short names to audio files in a direct dictionary. Then, we load the stream, assign it to an audio stream player, and call play. Volume changes the level, while pitch scale changes the pitch and playback speed. One player can replace its current sound when another player starts. So, later we'll use several players for overlapping hits. But, you might notice that we have some audio over here in our folders. Now, make sure you go through them and basically find what you like. Uh what we're going to be using are certain things like knife slice. So, you can hear, it kind of sounds like an attack. So, to do this, what we'll do is we will create a new script over here called audio manager. Now, I want to actually pause I want to get you to pause the video and go ahead and auto load this script. If you don't remember, we're going to go to project settings, go to the globals, select script, we'll select the audio manager, and that's it. We'll open up our audio manager over here and pop it in. Extend node is fine. What we're going to do though is add a couple uh variables. The first thing we need to do is get our audio dir um dir, which is basically where is it? And that is in assets {slash} audio. Now, the sounds are basically the actual files that we're looking for. As you can see here, we have like knife slice, chop, things like that. And those are the audios we're going to use for our current game. Once we've done that, we want to go ahead and access our player, which we can do so by getting our player and saying equal to audio stream dot new. Oh, sorry, we're not doing that. Our player is meaning audio stream player. All right, I misspoke there. We're basically making our audio stream player and then adding the child player. And we can do this in our current scene or our current script because this is an auto loaded thing. So, what happens if we ask for a sound name that isn't in the dictionary? With get, we can provide a fallback value. Here, we use an empty string. Then return if there's no file path to a to load. An empty string is still text. It's different from a missing object. Square brackets are useful when we expect the key to exist. For those optional lookups, get lets us handle it being absent. The resource path also needs to match the imported file, including the folders after res {colon} {slash} {slash}. Once we've done that, we want to make our own function called play. And this is literally just to play our uh audio, but there's a bit too more to it. We're going to be able to control the volume, the pitch, the stream, but we're also going to have a couple return functions just in case so a file not it doesn't exist, um if stream doesn't exist, then we'll return. Now, the important obviously part here is to get the file, which we'll do by saying sounds dot get with the name and our actual audio. So, we're basically finding which of these are we actually finding, right? Which of these do we look for and load? Cuz over here, that's where we actually load it. We say audio dot third plus file. That's basically what all we need to do. Once we've done that, we want to head over to our weapon controller, which we added previously. And in our ready function at the very top, we want to add this uh new signal where we're connecting hit landed on hit landed. This is basically going to be a new function that we create at the very bottom, literally just called hit landed. Once we've done that, we want to go ahead and actually play our audios. What we'll do is basically call hit heavy if the current is heavy if you recall that, otherwise we'll play slash. Now, if current is heavy, we'll also play hit stop and shake camera. These aren't audios, these are the game manager things that we added previously. Now, obviously we have a couple of problems, which is these. Now, these are supposed to be numbers if you recall because if we go inside of these, they need duration, things like that. So, at the very top, we'll go ahead and add these uh variables. We'll add constant quick hit stop, quick shake, and heavy stop, hit stop and heavy shake. Okay, now we can finally test what we have. Let's go ahead and close everything and hit play. And obviously we see an immediate problem here, which we can look for by clicking it, and it is telling us our base sprite scale.player sprite.scale doesn't exist. Um so, it's saying the something is null. But we can actually see right here in the members that pre-player sprite is null, uh which actually would make sense because we renamed it recently to sprite.2D. So, let's go ahead and uh make sure we change that if you did that. All right, there we go. And you can see here that it already kind of worked with the weapon on me, so I'm already getting hit. And I can also start hitting our player or dummy, and it works pretty nicely. Cool, we have a lot of things actually working, so let's actually also check the heavy. Yeah, and then there you go, it works. We have the particles kind of working and everything. Okay. Now, my promise from previously is to show you what the particles would look like inside of Godot. Now, what we're basically doing by in code is as if I just manually created this CPU particles 2D and then I'm setting these two these variables. The amount, the texture, the time, lifetime. You can see that we have one shot, we have explosiveness over here which goes to one. We even have other things like randomness if you want to set that. We also have the emission shape which is kind of how the shape will look like or start from. So, for us it's a point. We just want to start from this one point and go outwards from there. We also have initial velocity which we also set. There is angular velocity but that's more so like the angle of each little particle which is kind of hard to see in this case so we don't really care about that. We have the scale, we have the color which we did set and of course other things. There's a lot of different variables you can definitely check out. Um but this is basically the idea. If you want to actually see what your particles look like, then this is where you would do it. An important parts to look at here is the direction is set to 1 0. So, if I go ahead and set that to zero and emit that, you'll see that it just goes straight down and that is because of the gravity. But I won't basically but if you actually go through everything and set all the variables the same, you should see the effect that we created earlier. All right, at this point we want a damage number to pop up when we hit something but the damage might be a decimal. And we probably don't want those on the screen. So, we'll round the displayed number and turn it into text. That's the basic idea of what we're going to do. We're still using the original number to calculate the health but we're just showing a text that actually is nice to see on the screen. Then we'll move the label up and fade the alpha with twins but we'll add a little bit more. So, let's go ahead and close this and head over to script. And we want to head over back to the juice script. At the very bottom, we're going to add a new function called function damage number. It's a a static as well. It's basically going to pop up our damage number. So, we have um similar things, world position, amount, color, uh and crit. This is for later, but we will add the crit for now here. Inside of this, we're going to create a label because this is what we show our number on. So, we'll add a label. We'll set the text to the amount. It is important that we set it to a string. We'll take the amount rounded down uh rounded I'm not actually sure if it rounds down or up. Um I believe it just rounds to whichever one, up or down. I will set it to an integer, then we'll have a string of that integer. We'll also add a theme if we want our own color theme, you can create that here. That is exactly where it is. We'll set the size if depending on the crit. Basically, 16 if it is a crit, otherwise it'll be 11. Tween steps normally run one after another. Parallel makes steps run together, which is useful when we want to change two properties at once. Then, chain starts another group after those two steps finish. Once we've done that, we want to now actually show this label, and we'll do that with a tween. This is cool because I get to set its positions Y and basically have it slowly go upwards. Once we've done that, we'll subtract it by 22 over a duration of 0.5. We'll also modulate its uh alpha, which basically means it's slowly going to become invisible, which is very cool because it kind of gives us that effect of a a number popping out and slowly disappearing. Now, to call this, we'll add it in the heart box, which we'll do again over here. We'll basically say, if damage show if show damage numbers, then we'll call our juice.damage_number with everything that we just created. Okay, so that's pretty much the uh damage number. That will work for both the player and the monster because this again again is in the heart box component. Okay, now the lunge. When a swing goes active, we push ourselves a little forward towards where we're aiming. For the direction, we use the weapon pivot. Global transform.x is the way the pivot is pointing, and that's where we're aiming. For the push, we reuse our knockback variable. It's already added to our velocity, and it shrinks back to zero on its own. So, setting it towards our aim moves us forward a bit and then phase out. We skip the lunge while we're dashing, though. Next up, we want to head back to the player controller and add a new function at the very bottom, and we'll call this a lunge direction. So, our lunge. Function lunge with the direction and a force. So, we're going to check if dashing or is equal to length less or equal to 0.1, then we'll just return. Now, the way this one will work is back inside of our velocity over here, we'll basically just add it to this, which is already being done so in knockback, because we already set the knockback. Okay. And to actually call this, we want to go ahead and head over to our weapon controller, and inside of the begin active function, we can add this right before the enable hit box, where basically we get the aim, we'll take our global transform.x.normalized, and check to see if we have the lunge method. So, we will lunge towards aim with 210 if current is heavy, otherwise it'll be 110. Now, at the very last line, we'll have a juice.squash weapon sprite with the vector one with 0.2 and 0.15. Now, this actually calls the squash function that we created earlier. Now, let's close one more time, hit play, and there you go. We now see that little squash effect. And it looks a lot better now. Now, before we move on, one thing you might notice, um and depending on if you change this or not, is the weapon changes size uh back to one, basically. It's it's kind of bigger, and that's because of the size of the weapon the sprite is going back to one. But over here in code, we set it Well, that makes sense because in here in code, we set it back to one, but obviously in the inspector, we changed it back to 0.75. Now, there's a couple ways we can fix this. Of course, we could just fix it here, but we want to make sure that this problem never happens again. So, what we can do is head over to the weapon controller script. At the top, I will add base weapon scale. In the ready function of this There we go, right here. We can do this at the top. We'll set our base weapon scale equal to our current weapon sprite.scale. This will essentially save whatever thing we have. And then over here we can just call our base weapon scale instead. We can also change the easing to the sprite slows down as it returns instead of stopping abruptly. Now, one important thing to kind of change on this is to make sure we ease the juice because if we are changing the scale we want to ease this. So, what we'll do is we'll also add a check here to see if node is valid, which we should have done before, but I apologize. I kind of forgot about that. And we'll basically add the set trans to also have ease out. This will allow us to ease the scale, but depending on what it changed to. For the sword, we'll need to save the starting scale and location before animating them. Otherwise, resetting them to a hard-coded scale could undo the size that we chose in the inspector. So, we'll animate away from the saved values and return to them. Now, another promise I forgot was we also want to add the weapon rotation. We'll do so by taking our current weapon rotation. We'll set or save the re- the weapon rotation over here in base weapon uh _rotation. And I realize we're doing this in the wrong script. This should be in the weapon controller. So, over here, we'll go ahead and do that. And there we go. I'll just add it to the ready. And now at the very bottom, we'll go ahead and add our animation swing. What this will do is basically take the arc that we want, which is going to be 120°. We'll take it to a raid rad. If it's heavy, if it's regular, then we'll do 90. This is basically just a bigger swing if, you know, if it's heavy. We'll set our duration to a longer duration depending on which one it is. The weapon sprite, we'll set the rotation equal to the base minus the arc times 0.5. And then we will rotate or we'll tween the rotation back plus the arc times the rotation. And then we'll of course set it back. So, this will set its tween to the rotation of we want and then this will set it back to its original position. Now to make this work, all we need to do is add the function animate swing right after the juice. Once we've done that, we can go ahead and close everything and see our sword swinging. Now it's actually moving and giving that rotation effect that we want. Okay, we hit the dummy and now several things happen. It flashes, particles appear, a sound plays, and the animation reacts. But all of that should start from a hit that we've actually accepted. Otherwise, we can make a rejected hit look successful. Then think about what happens afterwards. The particle finishes and gets removed. The damage number fades away. The sprite and sword return to the scale rotation that we saved. If we just reset everything to one or zero, we could lose a setting that we chose in the inspector. So, when an effect looks wrong, we got to turn off the others for a moment. Check how one starts, changes, and finishes. Then put them all back together. We've set the time scale to zero for hit stop. The timer that should restore it also uses game time. So, when will that timer finish? Which clock do we need for this to wait? Game time isn't advancing, so that timer won't finish. We'll use a timer that ignores time scale for that restore. Whether it processes while the tree is paused is a separate setting. So, we need to choose that, too. So, now one hit does eight things. The knockback from earlier in this chapter, the flash, hit stop, the screen shake, the particles, the damage number, the sound, and the lunge. Two of them do a lot more than the other six. Can you guess which two? Stacking them all doesn't really tell us which ones are doing the work because by the eighth, the other seven are already on. So, how do we know that the eighth thing that we added is even important? So, let's take off everything and put them all back one at a time. Which two add a lot? Now, my argument will be hit stop and knockback. Now, to see why I think this, we need to watch what happens during the hit. Hit stop is the game stopping for a few frames. Knockback is the dummy ending up somewhere else. With hit stop, we can get a moment to notice the contact. That literally gives our brain a like, I don't know, fraction of a second to actually notice it. With knockback, we can see the dummy move away from the sword. So, both make the contact feel easier to follow when it's actually happening. This is why, for example, when you get exploded by a creeper, you get, well, knocked back a little bit. Now, hit stops are always hard to notice when you actually don't know about them. Um they're not in every game, either. I don't actually think they are in Minecraft, but regardless, hit stop is very cool to add in your kind of game. Now, the flash, the shake, the particles, and the damage number, the sound, those changes what we see and hear. They're telling us a hit happened, and the lunge does move something, but it moves us on every swing, even if we miss. So, it tells us that we attacked, not that we hit something. So, the eighth one is pretty easy to argue that it doesn't make a huge difference in hitting. Now, this isn't a ranking for every game. It's just a test a fight, as well. And a fact that you like on one dummy might hide a next attack once there's a bunch of enemies on screen. It just depends on the game that you're making. But here's the thing, if one get hit feels weak, before adding another effect, ask yourself, when I hit something, does the game actually change? Does the time stop for a beat or does the thing that I hit actually move? If not, that is probably where I would start. Okay, at this point, try adding one more effect or changing one that we've already made. Give yourself about 15 minutes. This isn't one specific thing I'm asking you to do. You just try to be creative here. Make it easy to turn off and on and then compare the same attack in both versions. You should be able to explain what changed and whether it actually helped the fight or not. This is more about feel and just more about you being creative at this point. Try to branch off of what we've already been doing and just add your own thing. You could try a small directional camera kick, a different sound variation, or another sprite reaction. You don't have to keep it just because you built it. If it makes warnings harder to see or the difference disappears during combat, just reduce it or leave it out completely. Keep the version that helps you read it, the hit, and the actual game. Again, this is just your game now. So, at this point, just do whatever you feel like your game should have. If you want somewhere to practice writing this stuff yourself instead of just watching me do it and then copy-pasting, that's what Coding Quest is for. You work through a task, write real Godot script code inside the browser, and check the attempt in the browser. The Roguelike's first controller quest is completely for free, and I have a 7-day trial. The link down below it takes you to the campaign, so go give it a try. We can see and hear a hit now. We'll need that on every enemy. So, let's put a shared enemy behavior together before copying it everywhere. >> it. But that also copies the code for health, knockback, and death. Knockback is the push an enemy gets when we hit it. If we fix a knockback bug in the grunt, every copy still has the old code and the same bug. So, we put the shared parts in one base enemy script that the other enemy scripts build on top of it. Each new enemy adds its own behavior. How it moves and when it attacks. The grunt chases us, but the caster should keep its distance. So, which behavior belongs in the base? Health and shared state handling can stay there. Then the base calls functions each enemy can fill on its own, set up, or decisions. For example, a grunt can chase until it's in an attack range, while a caster can keep its distance. They don't need separate copies of the health code. We'll use inherited scenes for the shared node structure, as well. Then change the relevant sprite and settings for each enemy. We want to now make our very first monster. Now, to do this, we kind of already have a base. So, I'm going to go ahead and hit control D on the dummy and call this enemy base.tscn. Then go ahead and click okay, open it up, and inside of this, most of this is already correct. We want to go ahead and just rename this to enemy base. Make sure that the layer is five, because this is the enemy hurt box for the hurt box specifically. The mask is going to be looking at six, which is the player hit box. The hit box component is going to be on layer seven and no mask. Make sure that we have a collision shape for this hit box. Once we've done that, we're going to go ahead and delete this sword for now. And instead, what we're going to actually do here is change this collision shape to a circle, and I'm going to go ahead and reset its transformation to the middle, and make it a little bigger. I'm going to also add a sprite 2D, and this is going to be our telegraph sprite. The cool part about this is that we're basically going to have something that telegraphs our attack before we do it. This is what makes our game actually a bit more enjoyable. We're going to go ahead and add a new script called enemy_base.gd. Go ahead and create it. Open up the script and here we go, enemy base. We want this to extend off the character body 2D, but it's also going to have its own class name, enemy base. Now, this monster is our AI. So, we need different states for this AI. It's going to have idle, chase, telegraph, attack, recovery, and dead. These are the basics of what our AI is going to have. Some different monsters that you make might have different things, but this is a good start. We're going to add some basic variables, max health, speed, attack damage, and attack knockback. We're going to go ahead and load our sprite, our health, our hurt box, our hate box, and the hit box collision shape. Now, if you're wondering how I kind of did that, I was holding control as I'm selecting. Once I've selected all those, I can go ahead and drag them into the script by first opening up our script here on the left and popping it in like so. Holding control before I let go. Once they're all on ready, there's a couple more things we need to add. We need to add a signal defeated and a couple more variables to keep track of our state. This will start with the state idle as the default. We're going to have a state timer, knockback, and player, similar to how our player has some of these things. So, we'll put the shared code in enemy base and let others extend off of it. That is called inheritance. The base can call a function that each enemy fills in differently. So, one chases the player while another prepares a charge. Our _on_ready function is one of those custom hooks. Godot doesn't call it by itself. We call it from the base ready function. We can also inherit the scene layout, so the enemies share the same nodes while using different sprites and settings. Once we've done all that, we want to add our ready function, which will set up a lot of what we need. We have the max health being set up, the current health, which is our health component, the died connect needs to be connected. We're going to have our source, damage, and knockback force, and then on ready. This is going to be our very first override point for subclass. Here, we're going to create the on ready variable or function, sorry. And don't worry about the rest, we'll continue on and fix these, so the errors will go away in just a minute. We'll add a AI process. This is basically just literally what it almost looks like, process, but for the AI. We're going to go ahead and add in our physics process. Here, we're going to say if the state is equal to dead, we'll go ahead and return. We'll also say, "Hey, if the player is null or if it's not instanced or it's not valid, we'll go ahead and find the player first." We will also call the process AI process with delta, passing it through. So, this is important to note that this this AI process is basically a AI physics process. If you want to go ahead and rename that to AI physics process, you're more than welcome. Here, we'll also check to see if player is valid, then we'll get our sprite.flip_h equal to the positions X depending on basically where it is depend like compared to our current value. So, if it's on the left side, we want to look towards the left. If it's on the right side of the monster, we want to look towards the right. Similarly to our player, we're going to go ahead and add velocity. We'll say velocity plus equals knockback. Knockback is equal to move towards zero and 1,200 * delta. This will basically literally just knock back our player or a monster, sorry. We'll also add a function very similar to what we did before. And finally, let's get rid of that pesky little uh die function by adding an our die function here. If state is equal to dead, we'll return state equal to dead. So, there we go. We'll set our velocity to zero, which makes sense. We'll get our audio manager and play the enemy death. We added that in a previous part, so if you don't have that, make sure you have that added. Now, what if two heads reach an enemy before it's removed? We don't want to count two defeats. So, we'll set its state to dead first and try that state when another hit comes in. Then, we emit defeated and call queue free. Queue free is scheduled deletion for the end of the frame, which means the node can still exist for the rest of its call. That's why we need the dead check as well. It stops us processing another defeat while the node is waiting to be removed. We're going to add player's position. This literally just returns the player's position as a vector two, only if the player is valid, otherwise it'll return our own global position. We're going to also check to see if has player. This return player if uh only not equal null and if the instance is valid. Basically checking a boolean, so it's just literally what it this function sounds like. Hey, do we have the player? We'll also add the uh der to the player, like where is the player in terms of direction or a vector two. And that's pretty much it. We'll also add distance to player. It's little easier here because there's a built-in function. We'll just get the distance to our player's position from the global position. Now, over here we have the attack area is not being declared, and that is because it should actually be the hit box component. So, I'm going to go ahead and rename it the hit box component to attack area. And I'm going to rename this to sprite. I'm also going to rename this to hurt box, and then this to attack shape. And that's it. I'm going to leave everything else the same. At this point, we should no longer have any errors. So, this is a full part of our script. Let me do a full review just in case you want to go chat back and check on anything. Okay, at this point let's go ahead and close this. We'll go to our enemy base. We're going to add the enemy script that we just created. The enemy base, I'm going to add that here. I'm also going to go to my Sprite 2D and I'm going to leave it actually. With the telegraph, we can keep this either hidden or empty. I'm going to go ahead and make it hidden as well as empty so that way we don't see it at all. Once we've done this, we now have an enemy base. Think of this as the template for our monster. Right click it and instantiate. Sorry, not instantiate. New inherited scene. I'm going to hit new inherited scene and here you will see the enemy base. I can go ahead and control S save and call it grunt enemy and we basically have the exact same thing. Now what we can do is extend the script on our own thing here. We're going to go ahead and rename this to grunt enemy.gd. Now the cool part about this is that in here it extends the enemy base. This is so cool because that script that we just wrote extends everything that we just wrote. So instead what we'll do is make our own thing called class name grunt enemy that extends enemy base. I'm going to go ahead and delete everything else and only have attack range. Once I've done this, I'm going to also add our on ready. This will override our previous on ready inside of the enemy base with these new variables that I want. Now if you want to export these numbers, um you can do that too. I just like doing it in code sometimes. It's kind of a nitpicky thing I like to do. And lastly, the cool part here is adding in our match process with match state with idle and chase. We'll set our velocity over to the direction of the player times speed. I'm going to rename this to grunt enemy and save. Once I've done that, I'm going to also change the main sprite here to 108. That's how 108 I find our sprite and change this over here. And there we go. Now, there's obviously a few other things we want to change. For example, this capsule. You'll notice that this capsule basically takes off the enemy base. Now, the problem with this is I can't really give it a new one unless I kind of clear it and it's kind of annoying. So, what we could do is over here, reset this, it's save, go back over here, and now we have to give this guy our own shape. And now we can give him a proper collision. I'm going to go ahead and do that for the other two collisions as well. I'll go ahead and reset those, go back to the grunt enemy, give this a capsule, or not a capsule, sorry, a circle, make it a little bigger than the original collision shape, then give this one the hit box, again, a little bigger because this is where we hit the monster or the player, sorry. So, it's like the attack area. Okay, now what we can do is close the enemy base. We're not going to need that for now. Go ahead and go to the main. We're going to delete the dummy. We're going to delete the hazard, and we're going to add our grunt that we just created. And now finally, we want to go ahead and test it. And now you can see it kind of worked. It faced us a little bit, but it ran away. The little monster that we were supposed to fight just didn't fight us. It's not really attacking me. It's just basically a thing with damage aura that has legs that runs. Okay, now the reason this probably isn't working is because if we notice that we're trying to access the player over here, right? We're basically saying, "Hey, player is going to be equal to get tree. get first node in group player." Now, this is cool, but what does that even mean? What are we doing group player stuff like we haven't done any of that. So what we need to do is head over to the group section on the top right in our player. We're going to go ahead and press the plus button. Type in player. We'll go ahead and hit create. And now our player is added to the groups or the it's added to the group player. Now in the enemy base, we want to do a similar thing but for the enemy. So we're going to go ahead and add this to the enemy scene. We'll go ahead and save. And now if we go over to the main, you'll see that they're added to the respective group. And now we can see that it's following me. That's because it's able to find my position. Now obviously you can see the problem with its attack is still kind of an issue is it's just kind of hitting us constantly and then kind of hard to actually fight it. Barely even a combat. Um but we can kill it and that is very cool. We do kind of have a workable monster. Now this monster, the grunt, has a hit box. The area where its attack can hurt us. For us to dodge the swing, the area only switches on during the swing. Once the grunt starts swinging, it finishes the swing even if we've moved away. So that way it can miss. And while he recovers, that's when we can hit it. Now we could just make the grunt hurt us whenever we touch it. But then there's no swing to watch and no moment to get out of the way. But let's expand it a little bit. So inside of our enemy base script, I'm going to go ahead and minimize all these functions so we have a bit more space to look at here. And I'm going to add a new function now at the bottom. And we're going to call this enable attack area. Here is where we're going to actually essentially have the attack happening. We're going to create attack shape as a circle shape 2D. We're going to get its radius equal to radius which is over here. And we'll get its position equal to the offset, its damage equal to our own attack damage, knockback force equal to attack knockback, and to reset the hits. We'll also get our attack area set deferred for both these to monitorable equal to true, disabled equal to false, similar to how we did the player. So, this is almost the exact same thing, if you notice, that we did previously in one of the previous uh parts where we did this. You'll notice that it's very similar. Obviously, here we're using a rectangle, but it's a very similar concept. So, of course, because it's similar, we also need to disable the attack area, and so we'll do that by doing the exact same thing, but set deferred uh to false and true. Once we've done that, we want to go ahead and call this in the on ready or in the ready, sorry. Disable the attack area. Once we've done that, we also want to add a couple new variables. We'll add attack cooldown, attack active time, recovery time, and a CD. Sorry, I just realized I wrote the wrong script. We want to add that inside of here, inside of the grunt enemy. Inside of the grunt enemy, this is where we're going to start expanding the logic of our actual behavior for our states. Now, the cool part here is once I'm chasing or if I'm idle, if player, if has player, and the distance to the player is within the attack range, then we will enter attack. This is where we will finally do the attack stuff. So, what happens when we attack? Well, we want to add our state here for match state. We'll take our state timer minus equal delta, and we'll basically switch to the enter recovery once our state timer resets. In the recovery state, we'll go ahead and add a recovery here. We'll basically say velocity is equal to move towards zero at a rate of 700 times delta. So, similarly, once that is done, we want to set our state timer minus equal to delta. Once it's zero, we'll go back to chasing. Now, outside of all this, we need to get rid of these errors, and we'll do that by adding the attack enter function first. Or the enter attack. This will basically set the state to attack because we never did that here or here, sorry. Um and then we'll take our state timer, make it equal to the attack active time, get our direction to the player, and enable the attack area. That is the thing that we just coded inside of the enemy base. We'll set our velocity equal to direction times 120. Then, we'll go ahead and enter recovery function. And it's basically the same disable, that recovery, recovery time, and attack cool down. Now, I'm noticing this problem over here. Uh, that that should be without an underscore, or at least that's how I have it in my reference. Uh, so I'm going to delete the the underscore here in the AI process. Now, nearly half a second where it stopped and can't do anything. That's for the recovery. So, this is kind of important because we want the monster to basically recover for about half a second. It's basically a window where they it can't do anything, where we hit it, and it's just sitting there, basically allowing us to have that uh, cushioning to actually be able to hit it. So, let's see if this works. Okay, it seemed to work the first time, which is good. So, let's see if it works one more time here. Okay, it worked that one time. So, it's working, but it's a little buggy. And it kind of makes sense because what's happening is we basically never reset the attack with our cool down here. There we go. So, we right before the master uh, state, we'll go ahead and check for CD and subtract uh, delta. So, let's go ahead and give that one more try. I'm attack, hit me again. After a little bit, he recovers. Now, I'm able to walk away. And then, yeah, this works pretty nicely. Wow, that knockback was very bugged. Um, but that's okay. We'll take a look at that in just a bit. Imagine we're making a training dummy that can take damage, but never chases us. Do we need to rewrite its health and death code? Which parts can we keep, and which decision functions do we just do nothing? So, take a minute to just figure that out before the answer. Well, it can reuse health, hit feedback, and the shared death handling. Its decision hook can do nothing. So, it can still be hit and defeated without copying those functions into another script or adding movement that it might not need. Okay, before you try this one, remember where our grunt gets its numbers. It's on ready function sets the health and the speed in code, and that runs after the inspector values are loaded. So, if we inherit the grunt scene and only change max health and speed in the inspector, on ready just puts 50 and 95 straight back in. Instead, give the new enemy its own script that extends grunt enemy. Copy the grunt's on ready into it and change the numbers there. That way, it keeps the grunt's chase and swing with the new health and speed. What if a grunt had less health but reached us much faster? Make an inherited enemy scene and try that. Try about half the health but nearly twice the speed as the starting point. Give yourself about 15 minutes to do this. Compare how quickly it reaches you and how many hits it takes to defeat it using the same weapon every time. Okay, we should be able to change those settings while reusing the base damage and movement behavior. Half health won't necessarily mean one hit. That depends on the weapon damage. So, check the actual values. This is a useful variation and later we can change its movement decisions as well if we want it to fight differently. Our enemy has the shared behavior that it needs. Now, it needs an attack and we need a chance to see that attack coming. So, what if this swinging monster, the grunt, attacks us as soon as it reaches us with no warning? We'd have less chance to see the attack and get out of the way. Lowering the damage makes the hit hurt less, but it doesn't tell us where to or when to move. So, before the attack can hurt us, the grunt stops and shows a red warning that matches the real attack. Pretty much about the size of the swing. Usually, if it's a little bigger, that's probably better. That warning is called a telegraph. It appears during windup. Then, the hitbox becomes active when the attack starts. After that, recovery gives us a chance to actually hit it back. This is a very common state machine back and forth in a lot of games. Souls-likes, obviously this one, the roguelike, etc. The warning doesn't cause damage itself, though. Its shape needs to match the area that will hit us. And it needs to last long enough to react. We'll connect it to the attack states and warning and hitbox change at the right times. How do we want to continue finishing our telegraph node? Right now, it's just hidden and it doesn't really do anything. So, inside of our enemy base script, we want to go ahead and add our on ready variable here. We'll basically just get the node telegraph. And just make sure that it is the exact same. And if you need to drag it in, go for it. The first thing we'll do is at the very bottom, we're going to add a new script or a new function, sorry, called show telegraph circle. By default, we're literally just going to pick a red color that is almost 50% transparent. I say almost, but it's it's exactly 50%. Um so, you can see it here, the alpha is .5. This basically just makes a circle around our player. So, we'll have the rotation, the scale, the modulation equal to the color. And then the visible, we'll set it to true. Now, we'll also have a function hide telegraph, very simple. We'll just hide it. We don't actually need to change anything else because literally all we need to do is change the uh visible visibility to false and its position back to zero. This just allows us to reset its position on top of the player or on top of the uh monster. Now, what we can do is in the ready function, uh we can go ahead and just call hide telegraph. Um this doesn't really do that much, but it does allow us to just make sure it's hidden um inside of code. So, if case I ever forget to unhide this or whatever, then in code, it will always do that in in the game itself. Okay, now inside of the grunt enemy, we want to go ahead and add the telegraphing. We'll do that by adding export telegraph time. This is how long we're going to telegraph before we actually attack. Now, what we can do is we're basically going to just replace this line of code with enter telegraph. Now, obviously we don't have enter telegraph, so why don't we go ahead and make that? At the very bottom, we'll add a new function, enter telegraph. This basically allows us to create our state or enter our state telegraph, get our state timer. It's basically the general enter state, right? We're basically setting the state, timer, and we're going to show the telegraph circle, which we just made. Now, we need to edit the enter attack, which will do by adding the hide telegraph burst. And that's it. Now, obviously there's a problem. We don't have the enter attack anymore, right? There's no state that or thing that calls that. Well, that's pretty easy to fix. All we need to do is match our telegraph state. So, here we will match telegraph. If we are telegraphing, we will move towards zero, similar to recovery. We'll, of course, have our state timer minus equal delta. We're counting down. Once it hits zero, then we will enter attack. So, after 0.3 seconds or 35, that's when we will enter the attack. So, this way we basically have it like this. We are either in idle and then we chase, then we enter the telegraph. Once the telegraph is over, we enter the attack. Once the attack is over, we enter recovery. Once the recovery is here and we're done, we enter back to the chase state and basically loop all the way back. And now, let's give it a try. Let's see what happens. Now, we can see that it's not telegraphing anything, so let's go take a look at why. Inside of our telegraph inspector, we will notice that it is empty. That is why. Um so it could be showing up, but we just don't have anything visible. So, what we're going to do is go to the telegraph, and we're going to actually create our own texture. We're going to go ahead and click the empty, go down to gradient texture 2D, and here we go. We have a texture. What we'll do is take this color, and we're just going to set it to white on both sides. We'll select over here, and set this to white. And sometimes it might take a minute, but it will update. The Find the gradients and the video engine tend to be a little laggy sometimes. Um but now, let's give it a try. Let's see what happens. All right, there we go. There's our circle, or our um telegraph. Now, you can see that it's kind of all messed up because the size is not right. It works pretty much how we want it to uh interact with the player and with the telegraphing. Let's go ahead and save that, and hide it, and let's head over back into our scripts. Before the swinging monster, the grunt attacks. It pauses and shows a warning. That pause is the windup. How long should it last though? Because if it's too short, we can't get out in time. If it's too long, we spend most of the fight waiting for the swing. So, we try a few lengths against the grunt's through a swing and our real movement. We can also make the warning a bit brighter as the attack gets closer. Elapsed time divided by the full windup gives us progress from zero to one. And we'll clamp it to keep that range. So, let's head over to our enemy.gd. We're going to go ahead and head to the top and add a new variable, telegraph elapsed, or tele elapsed. At the very bottom, we're going to add a new function for the telegraphing, and this will allow us to tick the telegraph. Here, we'll add tick telegraph with delta. Basic idea here is we're going to basically just tick it up. So, we're going to have take our tele uh elapsed and add delta to it. The way we'll calculate this is get our total and fill. We'll get our max float with tele elapsed, the current elapsed plus the max float of the state timer with zero all the way to a 0.001, and then similar thing with clamp float with the elapsed divided by the total with zero and 1.0. Then we'll go ahead and telegraph the modulate.a with lerp float 0.25s and a 0.75 to fill. Once we've done that, we need to make sure that inside of either the AI process or the physics process, of course, we add the telegraph uh tick telegraph. And I will add it inside of the physics process, which makes sense. I'll add it right after the AI process. Once I've done that, I want to actually add to our show telegraph circle, and we're basically going to check to see if the telegraph uh is not visible, then I'm going to reset the elapsed time. This basically turns our warning into a clock. It doesn't just say danger, it says danger and here's how long you've got. You can read it without actually watching it animate. Right now, we want to go back to our juice.gd. You recall, this is where we make juice. At the very bottom, we're going to create a new function called material. This will basically allow us to edit the material just a little bit. Here, we'll make flash material with the material that we get, and then we'll set our spice material to that material. We're also going to create a new function called set outline. This will allow us to just outline the material that we want. It will allow us to basically just make it look a little better. And we can do that by getting the material. Once we do that, using the material uh function we just made, we'll get the outline width, outline color, and outline pulse. Then, of course, we need to actually apply this, so we'll go to the grunt enemy. Inside of the enter telegraph, at the very bottom, we will add set outline sprite true, color, and then true. And 1.0, sorry, I forgot about that. And then in hide telegraph, I'm realizing I added hide telegraph to the wrong script here. I'm going to go ahead and actually add this here. So, this is what we need. So, hide telegraph, uh and then set outline to sprite and false, but we're going to actually move this to the uh grunt enemy. And this will of course move it inside of the on ready. Go ahead and save, and the error should go away. Once you've done that, now we can go ahead and hit play. And we can see it telegraphs it by doing it like so. Now, of course, we can adjust this ever so slightly. We can do by me just making it a bit smaller here. Basically, reset it. And set it down to probably 0.6. If we hide it, we can of see what it looks like. There we go. Now, let's hit play. And there we go. And once I hit it, the knockback is incredibly strong. And there we go. We killed the monster. Before we continue onto the next part, which is for enemies of the same base, we need to kind of fix a couple things. Like, first of all, the telegraph is a rectangle. It doesn't really make sense. It kind of just looks weird. Uh another thing is the size doesn't actually fit the size that we gave it. Um it's just too big. And there's a couple reasons for that. Another issue is the knockback. You can see pretty consistent with the knockback. The attack shape is also shared between every enemy. So, you can imagine that's also a problem. And another question {slash} problem is is the grunt too fast? Um it does feel like he's pretty quick, and he's pretty fast to speed up to us, and it's kind of hard to get away sometimes, especially when he sticks to us. So, we're going to address these issues in just a minute here. Okay. The first fix, the telegraph of the rectangle. Okay, we need a round warning that fades near the edge. Stretching a solid square won't really give us that. So, we'll choose a color along the range, including transparent ones. That's called gradient. A gradient texture turns those colors into an image that we can use. We'll use radial fill, so the warning is solid in the middle and transparent near the edge. Here, we're using a radiant texture 2D, so it makes sense. Now, if I go ahead and go to the fill, and we go to the linear, and change it to radial, now, what we can do is go from fill from select this and put 0.5, 0.5, and then one and 0.5. This basically allows us to go from the middle all the way to the right. The edge and width, we will keep it 64 by 64 for now, but what we can do is take the far right color in the radiant over here, and basically set the alpha to zero. Now, we have an actual circle. Now, for the size, that is the actual width, but you'll see that the size looks a lot smaller anyways. So, that kind of fixes our problem with the size and the fact that it's a rectangle. And it simply looks a lot better now. Now, if you don't like that it's very shaded like this, what we can do here is basically just move this all the way to the right. Now, we have a more solid circle. It's kind of up to you on what you want to see here. I'm going to me keep it maybe in the middle like this. It does look a little odd, but I think that's kind of a good middle ground when it's red like so. And there we go. That's our hit box. That's our telegraph. Let's say we change one enemy's hit box radius, and another enemy's changes, too. They're probably using the same shape resource. Local to scene lets each scene instance get its own copy when it's created. Make unique separates a resource when we're editing it. We also need to check nested resources. A gradient texture contains a gradient, so having separate textures doesn't automatically tell us that the gradients are separate as well. Look at the resource that we're changing. For enemies with different warning sizes and colors, we need those settings to be independent. Now, the other fix, which is the attack shape is shared between every enemy, we can go to the enemy base, select the hit box component, collision shape, and up for course, we do actually need to give it a shape, so uh I've gone ahead and given it back the circle here. And inside of the resource, we can select local to scene. We can go ahead and actually do the same thing for the hurt box. So, before we kind of got rid of it, but now we can kind of put it back, and this will fix our problem being able to make this local to the scene. And of course, we can do this one more time with the actual collision of the box. Same thing, local to scene. Now, our enemy base is working again. Now, for the speed of our monster, go to the grunt. See here, speed is 60 or 95. That is pretty low considering our player speed is 180, but if we want to lower it even more to maybe 60, I think that's not bad, so I'm going to leave it at 60. I'm going to go ahead and close, hit play, and that feels a little nicer. It feels like a little slower towards us, and there we go. We've got a base enemy now. If we want to make another enemy, do we need to rewrite health, knockback, and dying? Well, no. It can reuse those parts and change the decisions that make it move or attack differently. For an attack, we show the warning during windup, enable the hit box during active, then leave recovery afterwards. But, the warning and hit box are separate things. Making one bigger doesn't automatically change the other. So, before moving on, stand near the warning's edge, and test the actual hit. If it looks safe, but still damages us, then something needs to be fixed. The player needs the warning to tell them where and when they can get out of the way. Okay, try a few warning durations on the last enemy that you made. Give yourself about 10 minutes and ask, "Can you dodge it three times in a row? Are you reacting to the warning or were you already moving before it happened?" Keep the speed and damage fixed when comparing the warning. Okay, a faster enemy can reach us a lot sooner. So, a short warning can leave us very little time to respond. But, the duration also depends on range, tracking, and the space around us. Use the repeated test, choose a value, then try the enemy beside another one. We want the warning to remain useful when the fight has more stuff happening. We can warn the player before an attack. So, what happens if the attack is a charge or a projectile? Let's make that enemy need different responses. So, let's say we copy the grunt, the monster with the swing, and give the copy twice as much health. Now, we have a different monster, and now we have to dodge more swings before it dies. But, we're still standing in the same place, doing the same thing, waiting for the same warning, and attacking at the same moment. It's very boring and bland. So, here's a test that you can use straight away. Describe the enemy without talking about its health, damage, or speed. What do you actually need to do when it appears? Do you attack it? Do you dodge? What do you do? What do you actually do as the player when playing against these monsters? So, for the grunt, we need to stay outside of the swing and wait for a chance to hit. That one's pretty easy already. So, what do we actually do differently against each enemy? With the grunt, we watch its melee range. With the charger, we move out of the committed path. With the caster, we need to track the projectiles while closing the distance and finding a space. The brute gives us longer warning before a stronger attack. Numbers here still matter, but changing these decisions gives us more ways to vary a fight rather than only increasing health. Okay, so what we're going to do is we want to get a new inherited scene from the enemy base. So, I want you to actually try that yourself before I go ahead and show you again. What we'll do is right click at the enemy base, like new inherited scene, and this will allow us to create this new scene. Go ahead and call this at the charger enemy. Go ahead and save charger enemy inside the scenes. Once I've done that, I'm actually going to duplicate the grunt enemy and rename this to charger enemy. Going to take the charger enemy script, pop it into the charger enemy scene. Pop it open. Open up the script. Change the class name to charger enemy. And now, the important part is to actually change some of the numbers. What if the charger keeps turning toward us all the way through its attack? We move aside and it just turns with us. So, we'll have it choose a direction during wind up and keep that direction when it charges. Now, moving out of the path means something. The caster will aim differently though. It can follow us while preparing a shot, but once the projectile is fired, that projectile keep keeps its direction. We'll test both so that way the warning matches the enemy that actually does. Not only do we want to change the numbers, we also want to add some different variables because this is a completely different monster. It's going to have a charge speed, charge range, cool down, uh which we kind of had before. Um wind up time, charge time, recovery time, which we also kind of have, and charge direction. So, think of this monster as a monster that will charge towards our player. In our function on ready, going to replace everything for now with these numbers. Scroll down just a little bit, and instead of attack range, we will put in charge range. Now, for enter attack, enter recovery, and enter telegraph, all of these, well, other than the telegraph, mainly the attack and recovery, we want to now enter wind up. So, this will allow us to go into telegraph, windup, and get the direction to the player, and show telegraph. But, we're going to show a rectangle this time. This one is actually a bit more important. Um it makes a bit more sense to have a rectangle rather than a weird oval. So, in this case, we're going to show telegraph rectangle. Now, of course, that means we have to change some of these. So, for example, this one will enter windup. Inside of the telegraph, we're going to go ahead and enter charge. I'm going to go ahead and also slow this down to 600. Change this to 800. This can stay as enter recovery cuz we do still need to recover. Scrolling down, right between enter windup and enter recovery, I'm going to add a new function called enter charge. This is where we actually charge. We'll hide the telegraph cuz now we're actually charging. We're going to attack. We're change the state to attack, and actually move. In the enter recovery, I'm going to go ahead and replace it with these. I'm going to have the CD as cool down, and so forth. Now, with the enter telegraph, I can actually go ahead and just delete this for now. Um we will probably change it. If you want to keep it just for reference, um you're more than welcome. But, we will be kind of replacing a lot of this with other ones. So, the first thing we actually have to replace is the show telegraph. Now, we're not going to replace anything per se. We're actually going to add this inside of the enemy base. Because here, we have the show telegraph circle. We want to do basically the same thing, but we're going to be telegraphing a rectangle. The way this one works is very similarly. We're going to have a rotation, but it's going to be equal to the kind of important, because what's going to happen is we're going to telegraph towards the player. So, wherever the player is, we're going to look towards the player. We're going to set the scale to a length / 64, and width / 64. The position, again, we're going to rotate it. Modular, and visibility very similar. Nothing different there. Now, back inside of the grunt enemy, or sorry, not the grunt enemy, the charger enemy, this error should go away. And if I go ahead and close this, and I search up 110, I can find a new sprite that I want to use, or any other sprite that, you know, you want to use for yours. And I'm going to use this guy. So, I'm going to go back to my main, search up charger, and add my charger to the scene. I'm going to go ahead and move the grunt a little further away, and hit play. And there we go. That was our rectangle, but you can see that the telegraph isn't really a rectangle. So, what we need to do here is go to the charger enemy, go to the telegraph. In here, I'm going to make sure I make this unique first before editing it. Then, I'm going to go to fill and just reset this, to be honest. That's pretty much all we need to do. Uh for this one, we do actually want to just change this back to fully white. And then we can go ahead and hit play, and now we see a proper rectangle. There we go. That's our proper rectangle, and I've noticed I broke the other one, and that is probably because I didn't make this unique. So, I'm going to go ahead and actually control Z that just a little bit, and reset this. If you did that by accident, um basically what happened is this resource is sharing the resource with the telegraph over here. So, we basically want to make this unique, so that way it doesn't do that. So, I'm going to make this one unique first, and then make this unique as well. Once I've made both of them unique, now, if I edit this and save, this should not be edited. You can see here, it's still radial. And then here for the enemy base, this is also still radial. So, going back here, we can go ahead and reset all of these, except for the gradient, we can probably keep that, and just change this to full alpha. Go ahead and save, and make sure this is not different. And then hit play one more time. Then this guy should not change. All right, there we go. Awesome. Our graph seems to work new for our charger enemy. Now before we move on, there is an obvious problem which is that you will have noticed the attack didn't really do much and that's because over here inside of the charger enemy state for the attack we're not really attacking anything. Cuz before for the grunt enemy, the attack would happen in the actual function, but we don't have that anymore. So inside of this attack state, we now need to add our velocity and this is our attack, the velocity. Because the player the this is basically this like enemy at charging at us is the attack. So this is the behavior of the attack. Okay, now let's sidestep the charger, the monster that rushes us along a locked path and hit it while it's still charging. We should expect a short push from our hit. The charger keeps setting its charging speed every frame here and the push from our hit called knockback gets added on top of that. Now we could lower the knockback, but that would weaken every hit on every enemy. Now instead what we can do when an enemy gets hit, it stops moving itself for a split second and that kind of fixes it. That pause is called hit stun. It's pretty common in a lot of games. The knockback moves it and then carries it on. If an enemy ever moves strangely like this, check every place the code changes its speed and direction in the same frame. Now we're going to go ahead and add a hit stun which we'll go ahead and view inside of the enemy base. Inside of here, we're going to add a variable hit stun, make it equal to zero. Inside of our apply knockback, we want to now change this. Because in here we're not very doing much. We're only knockback plus equal direction times four. It's kind of boring and there's a lot more we can do to this. There's also things that we need to check for. Basically, we need to check if the direction X and Y are is finite. If so, we'll return. Then, we'll take our knockback equal to direction times force. We'll also get our hit stun, make it equal to the max float of our hit stun, clamping the force divided by 1,800 with 0.08 and 0.02. two. Then, inside of our physics process, right after the AI process right here, for the knockback, it's very important is basically just between this and this. It could actually just be right here, but I'm going to put it right after Actually, I lied. I'm going to put it right after the tick telegraph. If hit stun is greater than zero, we're going to go ahead and reduce by delta, and then get our velocity equal to zero. All right. Now, our charger pretty much works. If I go ahead and hit play, you'll see that he pretty much charges at us after doing that initial thing. And if I hit him, he gets knocked back just a little bit. There we go. I killed him. And that's pretty good. Um we will be adjusting a lot of things uh soon with them. So, don't worry too much if you feel kind of weird with it. And obviously, if you don't like the numbers, then change them. Um obviously, the numbers I use tend to sometimes just be random numbers, and I kind of just throw them up there. But, I do encourage you to just change the numbers around as much as you want. This is one of the most fun parts about actually making a game is changing the numbers and seeing it work in the game. Um but regardless, we now want to do our caster enemy. So, again, once again, I want you to pause the video and create our third monster that is extending off the enemy base. Now, there's actually two ways to do this. One way what you can do is to duplicate the charger enemy, and just call it to the caster enemy. Inside the caster enemy, you'll see that it's pretty much the same as if I had done new inherited scene. And that's because I just duplicated it. We zoom in. I'm going to go ahead and go over here and search up tile 0 84 or you can kind of just choose yourself. Uh and here we go. This is our little caster monster. I'm going to save. But of course, we we need to rename this to caster enemy. We also need to attach a new script. I'm going to go ahead and duplicate the grunt enemy by hitting control D and calling it caster enemy.gd and I'm going to pop it in right here. Once we open this up, at the very top, we want to call this class name caster enemy. Quick check before we type the caster's code. We just duplicated the grunt script as caster enemy.gd. But look at the name at the top of the editor. The file that's open is still grunt enemy.gd. In this recording, the caster's code ends up in the grunt's file. So, for the next few test runs, the grunts on the screen stop and shoot, just like the casters. In your project, open up caster enemy.gd, give it the class name caster enemy, and attach that script to the caster scene. The grunt script stays the grunt. We'll check this connection again in lesson 3.6. And again, we will have different variables. Now, this one's going to be relatively different, especially with this one. We're going to have a projectile scene. Because we're going to be throwing a projectile at our player. That red arrow at the bottom is expected. The caster's going to fire a projectile, and that projectile will be its own small scene saved as a file. Now, preload loads that file once. When the script loads, and later instantiate makes a fresh copy of it every time the caster fires. We haven't made that scene yet, though. We'll build it right after this script, so for now, Godot can't find it. One more thing about the path. Our folder is scenes with a capital S. Now, Windows lets a lowercase S slide with a warning. But an exported game might not find the file. So, try to match the capitals in every preload from here on. Something that I kind of forget to do. Now, here we're going to have preferred distance, fire cooldown, telegraph time, recovery time, which is pretty similar to what we had before, and the damage, or projectile damage. We'll also have aim direction, which is pretty much the same as before, just called aim direction. Inside of the on ready, there's going to be a lot less here. We're going to have max health speed, max health, or health, health current health, and then state chase. It's going to immediately be chase, and then right here, on this line, we need to replace it both with the velocity thing with kite, and then basically the same line, but with preferred distance with 140. Now, kite is a function that we'll create in just a second, but we need to make sure everything else is correct. Now, telegraph is actually going to be pretty much the biggest part, and we're actually going to remove the state attack. Here, in telegraph, we're going to say velocity is equal to zero. Aim direction, direction to player, makes sense. And then we're going to show telegraph rectangle, just like with the the charger. And then we're going to do basically the same thing with the state, but we're going to also fire once it's done. Now, this is the attack, because that's where we actually fire the projectile. Now, for the recovery, we're going to do the same thing, kite. It's basically kiting the player, kind of moving away from him. We want the caster to keep some distance from us. If we're too close, it should back away. If we're too far, it'll approach. Between those distances, it should move sideways. Using a range like that stops it constantly switching between approaching and retreating around exactly one number. To move sideways, we need to be perpendicular to the direction toward the player. So, turn 90° basically. We can use that same idea for an enemy that weaves as it approaches. Basically, move toward the player, then add a small sideways movement. Now, kiting is literally just going to be It's going to be very simple for us. We're just going to create a function that moves away if we're too close to the player. So, here, here's our function. If not player, then velocity would just be zero, and we return. If we do have player, obviously, then we'll get at the direction, and if D is less than the preferred distance minus 30, then we'll go negative direction times speed. If it is bigger than it, then we will go towards the direction times speed at a slower pace. Otherwise, we will do a I can't even say this word, but it's a perpendicular vector rotated 90°. I'm not even going to try saying the word. Now, for enter telegraph, we actually can just replace this with a very simple three-liner. And then all we need here is fire. Now, in enter attack and enter recovery, we can actually just delete both of these. And then at the bottom, we'll add another function fire, which is very important. Hide telegraph, state is equal to recovery, state timer equal to recovery time, aim direction equal to the direction of the player, and then this is where we actually create the projectile and basically send it towards the player. Now, we're going to set it up next to us, but we're going to also send it towards the player in the projectile. So, that's the next part is actually creating the projectile. To do this, we're going to go ahead and create a new scene on the top right here. Go to other node, and we're going to find an area 2D that will be the base. We will also add a sprite 2D. And of course, a collision shape. Once we do that, we'll give this collision shape just a simple circle for now, just so we have an actual shape. We'll go ahead and save this as projectile.tscn. Okay, we have a projectile scene saved in the project, but obviously saving it doesn't fire anything. We need to create a copy when the caster shoots. Preload gets the saved scene, and instantiate creates the node for that copy. Then we add that instance to the running tree and set up the shot's position, direction, damage, and source. Keeping the source tells us who fired it. We also need to remove the shot eventually, though. It can disappear when it hits a wall, when a hurt box accepts the hit, or when its lifetime runs out. Otherwise, a missed shot could stay in the game indefinitely, and eventually you might just have 10,000 random shots existing in the world, which we don't want. We want to make sure that the area is on layer seven, not six, because you can see that we actually gave this its own thing, projectiles. We're going to go ahead uncheck the other ones. We'll rename this to projectile as well, and we're going to go ahead and create a script, projectile, but we're going to make sure we put this in the scripts folders. Hit create, open this up, and we'll go ahead and create a class name projectile. We'll also add some variables, speed, damage, knockback force, lifetime, source node, direction, and life. We want to also add this to a group. Now, I previously showed you how to add it through the groups. Now, instead, what we can do is add this in code. We can say add to group hitbox. We'll also connect our function body entered. The body entered function will connect right here. We'll call pop. Now, on that, before we actually create this, we'll also create the on hurt box hit, which will also say pop, and pop will do two things. Simply going to call our juice impact, and we're just going to create an impact here, and then the Q free that just destroys this projectile. Now, there's two other important parts is the setup of this object, which is getting the direction, the damage, the source node, and the rotation. The projectile has an area 2D, so it can tell us when something overlaps it, but what makes it moving? Unlike our character body, we're changing this position ourselves. Direction times speed gives us velocity, then multiplying by delta gives us the distance to move this update. The area can report an overlap, but it doesn't stop itself against a wall the way a character body does. We're moving it in contact callback instead. Very very fast or small projectile overlap checks can be missed pretty often between updates. We'll need a sweep swept collision test if we want it to handle that case reliably. Now, this is especially important for the next part because we're going to add our physics process that actually moves this projectile. Now, unfortunately, because we're using well, unfortunately, I wouldn't say unfortunately, but we're using an area 2D, not a body. So, there's no velocity. So, we're going to use global position to move this object. And it's actually pretty simple. We just add our direction times speed times delta. Now, the very last thing that we can do here is inside of our hurt box component, we can now also add a check for if the area has a method on hurt box hit. If so, there we go. We now have that uh signal getting sent. Okay, now we want a brute and a skitterling. Okay, so which parts do we actually need to code? They still have health, still get hit, and still go through attack states. What we mainly want to change is how they move and when they attack. The brute is slower and has more health and gives us a longer warning before a harder hit. Whereas the skitterling approaches while weaving sideways, so it puts pressure on us in a different way. Before we look at the scripts, look Think about which parts need changing. We still need to take damage through the health component. We still have windup, active, and recovery. Things like that. The new code mainly changes the movement decisions and attack settings. Let's start with the brute. Up top, we've got its attack settings. How close it needs to be, the cooldown, and then the telegraph, active, and recovery. That .6 second telegraph is how long the warning we want. In on ready, we change the stat In on ready, we change the stats it gets from enemy base. 120 health, slower speed, and a harder hit with more knockback. Then we copy max health into health component, so it actually starts full. Now, AI process is the decision part. Enemy base calls it every physics frame. So, this is where the brute decides what to do. While it's chasing, it walks towards us and once we're in range and the cool down's done, it can start the telegraph. Then each state just counts down its timer. During the telegraph, it slows to a stop. So, we can actually see the wind up coming. Then it attacks, recovers and only after that goes back to chasing. These enter functions start every state. The telegraph shows the warning circle. The attack turns on the hit area in front of it and lunges a little bit. And recovery turns that off and starts the cool down. This skitterling uses the same states, just with different numbers. The telegraph's only 0.1 8 seconds. The cool down's short and there's one new setting, weave amount. It's fragile, 18 health, but it's fast. And each one gets a random weave phase. So, a group doesn't all wiggle in sync. Now, the weave is the new part. Orthogonal gives us the direction sideways to where it's heading. And sign swings between minus one and one over time. So, we push it a bit to the side back and forth while it still closes in. And after it bites, it backs off instead of standing there. Which is what Which is what lets a few of them take a turn at us. So, same health component, same attack states. The new code is really just how they move and when they attack. So, let's see each one on its own. And once you've added all of these inside of the enemy or inside of the main, we now have a bunch of different monsters coming to attack us. And there we go. We even have the big guy, the brute is really scary and now we just have a lot of combat and things going on. This feels a bit more fast-paced now. It feels a bit more like a roguelike. Now, there are still a lot of things missing, which will bring us into the next part, which is finally our boss with a tail. So, let's go take a look at that. The charger commits to a path, while the caster keeps its distance and fires a projectile. They need different decisions, but they can still use our shared health and hit code. The projectile then needs its own movement, contact handling, and lifetime. Otherwise, a missed shot could stay around forever. We also added hit stun. Without it, the enemy might try to chase us on the same update that knockback pushes it away. For the next enemy, work out which behavior changes before copying any of the common code. Okay, you change one enemy's warning shape, and another enemy's warning changes as well. They have separate nodes. What would you check before changing the attack code? Well, we need to check whether those nodes use the same shape or material resource. Separate nodes can still reference the same resource. Make the settings independent when needed. Then change one enemy again and check that the other stays the same. What enemy would make us fight a grunt differently? Try making a small variation, then put the two together. Give yourself about 15 minutes for a small version. Compare that pair with two grunts and describe what you do differently. It could change the space available, the timing, or which enemy you deal with first. For example, a ranged enemy can make us keep moving while the grunt winds up, or a fast enemy can approach from the side. Test each enemy alone as well, so we can tell what the combination added. A stat change can work as well, but check the actual behavior instead of assuming that more health always creates a more interesting encounter. These enemies make us react in different ways. Now, let's put several attack choices on one boss and show which one of it is about to use. Now, we could just give a boss a lot more health, but that can mean repeating the same dodges for longer again. So, it kind of brings us back to our previous problem. Our boss can use three attacks, a slam, a volley of shots, and a charge. We need to move differently for each one, like the other enemies. It's basically three enemies in one. That's basically what makes the boss a boss. But obviously, the boss will warn us. It attacks and then pauses to recover. This makes the game obviously a lot more balanced, but again, adds variety. Each time it prepares an attack, it picks one of the three and then warns us which of the three. A big circle for the slam, a line for the charge, and a small purple circle for the volley. Now, of course, if you wanted to make this harder, you could make the slam and the volley the same warning. That would probably make it a lot harder, but again, it adds a little bit of variety to the game. Now, adding these three patterns don't automatically make a good boss either though. If one dodge works against all of them or the warning is too hard to tell apart, which I just said, we still have something else to fix. All right, so in order to uh start our boss, we want to create a new script here called boss enemy.gd. We'll go ahead and create that. And because we have so many scenes open, I'm going to actually close tabs to right, basically closing everything except for the main. Once I've done that, I'm going to go ahead and duplicate the caster enemy and call this boss enemy. Inside of this caster enemy, I'm going to double click the name boss and rename it to boss enemy. For the tile, we're going to do 8 087, and I'm going to go ahead and drop that into the sprite 2D. For the transform, I'm going to go ahead and make him four, which is incredibly big. So, we want to make sure we scale everything to size. We don't scale it per se, but we make sure we adjust the sizes of everything. Right, once I've done that, I want to go ahead and get our script and pop it into this node boss enemy. And here we go, we now have the script boss enemy, which doesn't have anything. We want to go ahead and first replace the first script by extending the enemy base and having the enemy or boss enemy as our class name. The boss is winding up. Okay, winding up for what though? A slam, a charge? Knowing the state doesn't tell us which attack it chooses. So, we need to remember both. Pattern tells us whether it chooses to slam, volley, or charge. State tells us which part of the attack it's in. That lets us reuse the state changes without making a completely separate state machine for every attack. We'll pick the pattern randomly, which means it can repeat. Three possible attacks doesn't mean that we get each one before any repeats though. Whatever it chooses, the warning needs to show us what's coming next. We'll go ahead and add a couple variables here. The first being the projectile, because we might use that for something else. We'll have pattern, slam, volley, and charge. These are basically just different attacks or patterns that we will have for the boss. And this is kind of important, and this is because it adds randomization that we can select from. We'll have our pattern, move timer, and charge direction. And of course, we will need to get our on ready variable, basically adding all the variables or setting all the variables, and we are also going to add this guy to the group boss. Inside of our function prod AI process, we're going to start off with the idle and chase. And there's going to be quite a bit here, but basically we're going to get the distance to the player and the direction to the player, and basically depending on the direction and everything, we'll set our velocity to three different things. If the move timer is less than or equal to zero, we will choose a pattern. Now, this This the fun part of making a boss AI. This is a very simple way of doing this. The idea here is that we basically have a function choose pattern that is going to randomly pick between the two or three patterns that we set. To start off with, this is what we will have to essentially have. We'll have a built-in function pick random and it's just going to pick one for us and it's literally just going to pick one of these three and set it to pattern. Once we've done that, we want to set our state to telegraph variable at time at 0.7 65 and then we will match the pattern depending on what we're doing or the behavior of the pattern. This is where we'll actually have the different things happening. Slam will show telegraph circle but it'll be red. Volley, same thing but it'll be purple. And then charge, we're going to do the same thing but we're going to get the direction and show telegraph rectangle. This basically allows us to not have the behavior just yet but it allows us to telegraph in three different ways. This way the player knows what's going on and they're not just shown in the dark and random attacks are going at them. That's just un-fun and not exactly enjoyable to play. Once we've done that, we want to go ahead and create execute pattern which is very similar. We're just going to hide telegraph first. We're going to get our state equal to our state attack, match the pattern with slam, volley and charge and depending on what which one we're doing, we're either going to enable attack area which is just like the slam. We're going to have shake camera and head stop, pattern volley and ring fire. We'll also have dot charge as a pattern and if so, then we'll enable attack area and shake the camera. For the fire ring, cuz we don't have that function, let's say the boss fires eight shots in a circle. We could write out eight different directions but what if we want 12 later? Instead, we'll repeat the spawn code in a loop and calculate each direction from its place around the circle. Range count gives us indices from zero through count minus one. Divide the index by the count then multiplied TAU or tau. And we have an angle around the circle. Tau is a full turn in radians. Cosine and sine give us X and Y parts in that direction. Use a float in the division, so we keep the fractions. Then with eight shots, each angle is 45° apart. We stop before a full turn because that would put another shot on the first shot. This is where we will have our projectile. So, basically similar thing, we're just going to fire these rings in a uh for loop. So, the way this works is we're just firing outwards um in a circle and firing different projectiles in that circle. So, it's not necessarily towards the player, but it's a 360 ring that we're going to uh s- fire a ring, right? That's the idea. All right, back inside of our match state, we want to go ahead and add the rest of our states. Telegraph, attack, and recovery. Telegraph will just move towards and execute pattern. Attack, we'll say if the pattern is equal to charge, we'll set our velocity equal to the charge. But, if we're on a wall, then we'll enter recovery, which we haven't actually added any walls yet, but we will get to that eventually. Uh otherwise, we'll set our velocity equal to velocity. move towards zero at a rate of 600 * delta. We'll check to see if our state timer is less than zero and again and enter recovery. We'll set our velocity to zero at a rate of 500 * delta. And then similar thing, if the state timer is less than equal to zero, basically we're out of the recovery state, we'll go back to chase and set our move timer to a random range between 0.6 and 1, which is really cool because we get to change things randomly. Now, it's cool and important that we do this because having randomization in our game is incredibly important, especially when it comes to a boss battle. Now, once all of this is done, obviously we are getting a a errors here, which we need the function enter recovery. This will disable the attack area, get our state equal to the state.recovery, and get our state timer back equal to 0.7. Once this is all done, I'm going to go ahead and delete all my other enemies and pop in the boss enemy. And let's give it a try. Okay, so the telegraph seems to be working. That's nice. However, he doesn't really seem to be getting close enough to me. Now, the charge obviously in this case doesn't matter because he will get close to me in that case. But all three attacks seem to be working, or all three patterns as we might like to say. You might have noticed the slam and the volley warnings came out as squares, not circles. Now, we made the boss by duplicating the caster, and the casters came from the charger, whose warning texture we turned into a plain white square so we could draw a path. So, the boss copied that square. One texture can't be a circle and a path at the same time. So, in lesson 3.6, we'll keep both shapes in enemy base and pick the right one for each warning. For now, the color and the size still tell us which attack is coming. The main issue is mostly the distance between him and the player. Now, inside of our projectile, the sprite 2D is empty. So, that's a pretty big problem. The texture just doesn't have anything. So, what we can do is just fill this out by adding whatever works. Um we can add, let's say, one of these either torches or maybe a weapon, that could make sense. So, I'm going to go ahead and just add a weapon. A double-sided weapon kind of makes the most sense to me, so that's what I'm going to add. I'm going to close the projectile and head back to our boss enemy. >> Okay, and when it comes to the range of the boss or anything else, that is specifically right here. The inside of the process, this is the distance that we're looking for the player. But then in the execute pattern, this is where I actually attack. So right here, for example, the enable attack for the slam, we would want this to be 22 if I want it to be closer because this is the radius. For this one, if I want the charge to be wider, I can change this to 15. Now, I'm going to actually go ahead and change this one right here to line on line 70 or line 35 to 45.0. Now, we can go ahead and hit close and check it out. Okay, there's our charge. There's our charge again. Oh, there's our melee or our ring thing projectile. He's going to do it again. All right, for our slam, it doesn't seem to actually be affecting anything, and that's mainly because right now our hit box basically just isn't as wide as our telegraph. So what we can do is make that a little bigger, and if anything, I'm actually going to make this a little smaller as well. I'm actually going to reset this to 0.6 and just expand it from there and do that. I think 1.17 is good. One thing about what we just did, changing the warning scale in the inspector doesn't stick. Show telegraph circle sets the scale from the radius that we pass in. Every time the warning appears and enable attack area sets the slam's hit radius and the same way. So right now, the slam warns us with a radius of 80, but it only hits within 22. Now, the fix is to pass the same number to both calls. In lesson 3.6, we'll put that number in one constant, so the warning and the hit can't drift apart again. Now, the question is, what about the end of the boss fight? If the boss never changes, the last part can just repeat the dodge that we've already been learning. Now, of course, this might be fun for inexperienced players, but as the player plays your game more, they become more experienced, and they want more variety. So, again, once our boss drops below half health, it can pause for a little bit before attacking, fires a volley of 10 shots instead of eight. Basically, we change its variety when it's after or below half health. A lot of games do this. A lot of Souls-likes do this very, very often, and for good reason. It's just good boss design. It's very frustrating at times, but it again just creates that variety that players look for when they're experiencing the game. We could speed it up a little bit with every hit instead as well, but a slow ramp is hard to notice. One threshold at half health is a change that we can actually see and test. Now, we can also add effects that announce this change. A camera shake, a short freeze, a ring, and a color shift. But the boss stays below half health for the rest of the fight. So, should that affect the play in every frame? Well, no, just once. We keep a flag, a stored yes or no value, basically a boolean, that says whether the announcement has played. Then we test the boss just above and below the health. Okay, our next part is to continue adding inside of our boss here. Let's pop this out. I'm going to hide these functions for now, so we have more space, and add a new function called enraged. This will allow us to know if we're enraged boolean-wise if our ratio of our health is less than 0.5. So, to apply this, we want to go ahead and go to our choose pattern. And for this, we're going to set it to 0.5 if enraged, otherwise it'll be the default of 0.65. Inside of the execute pattern for the fire ring, we will make it 10 if enraged, otherwise eight. For the enter recovery, I'll go ahead and set the state timer to 0.5 if enraged, otherwise 0.7. Now the last one over here, we're going to set the move timer to two different ranges. Uh basically if it's in range, this, otherwise one. Now inside of our G ju juice script, we want to add a new function here. This is going to be an expanding ring. So we're going to call it function ring, and the basic idea here is we're going to draw a line 2D and set a bunch of different variables, closed width, default color, the Z index. This makes it basically all the way in the front of everything. Then we're going to add child to the world, set our global position equal to the position of this position. And now obviously we have the problem, which is we don't have the circle points. To draw a ring, we need points around its edge. One vector two only gives us one point. So we'll collect them in a packed vector two array, a compact array for those values. Then the line can draw through the lines in order. You'll also see array with a type in a square bracket, like vector 2I. That tells Godot which type of entry the array can hold. Square brackets after a variable name mean something different. Point zero gets the entry at index zero. We'll keep that distinction clear when we start indexing these lists. So we'll add another function here called circle points, taking in the radius with steps, and we'll basically for loop through the steps, and take TAU, which is pi times two, times float of I divided by steps. Then we'll append it inside of the points and return the points. Now back inside of the boss enemy, we want to go ahead and add a new variable on the top as enraged. And then inside of the AI process, right before the match state, I'm going to go ahead and check if has not enraged and enraged then we will call on enraged. That function will add at the very bottom. On enraged where we'll basically shake the camera, hit stop, set the sprite modulate, and set a ring which we just added. Now, one last thing we want to add is the variable level. Which will scale with the floor. This will kind of come into play later, but we will have this for now and set our level, get our level equal to level which is the variable here, get our max health, and basically just scale everything depending on what level we are. Now, at the moment this doesn't do anything unless I actually use this in the ready function. But this will help us later on once we have scaling. So, you can imagine this is really good for roguelikes because we can change the the stats depending on what level we're on or what floor. Okay, the charger travels 100 pixels and has a body radius of 10. We only draw a 20-pixel circle at its destination. Is that showing everywhere the charger can hit us? Think about it. Sketch the warning that you would use. The path is dangerous, too. For this rectangular warning, we'd cover the 100-pixel travel plus 10 at each end. So, 120 long and 20 wide. Centered halfway along the travel. And there you go. Then compare that warning with the actual moving it's hit shape. Okay, try adding one more pattern that's only available after the boss becomes enraged. Give yourself about 10 minutes for a simple version for this. Now I'll give the attack warning. Now after seeing it once, can you tell what it did and how you might avoid it? Then try avoiding it on the next attempt. A double slam is one possible experiment, but the second hit also needs a readable queue or timing that the player can learn. Don't just try to make the warning shorter because it's a later phase. Those kind of fights tend to become very frustrating and not fun to actually play. Test whether there's enough time to respond while the other patterns are still in selection. Then adjust the damage and timing separately. We can fight the boss and the other enemies, but how does the room know that we're done? Let's track the encounter and show the values we need on the HUD. Okay, now we defeat the last enemy in the room. How does the room know that it was the last one? The room keeps a count of its enemies. Each spawn will add one. Each enemy tells the room when it's defeated and that takes one away. At zero, the room will be clear. Now that only works if each enemy reports its defeat exactly once. Otherwise, the count can still hit zero while the enemy is still alive. All right, so our first step for this next part is we're going to duplicate main. We're going to call it combat room. Hit okay. Open up combat room. We'll also put enemies, projectiles, and pickups under their own container nodes. Later, we can change the rooms or floors that give us a clear place to find and remove the temporary objects. And instead of the boss enemy, I'm going to delete that for now and add a node 2D. I'm going to duplicate this twice. This first one is going to be called enemies. The next one is projectiles. And the last one is pickups. We're going to also go ahead and add the pickups node to a group called pickups. We'll do a lowercase. Hit create. We'll do the same thing for the projectile. I'm going to go ahead and copy that. Hit create on that as well. And our player is already here, so that's fine. And now we're going to go ahead and make a new script here called room controller. Also, real quick, I'm going to rename this combat room, and go ahead and add a room controller script, and attach it to the combat room. I'm going to hit save, and I'm actually going to right-click my room controller, and close tabs or close other tabs. That way, things kind of just feel a little less cluttered. I'm going to go ahead and name this class name room controller. And now we're going to preload all the scenes that we just made. Once I've gone ahead and done that, I'm going to go ahead and add a more variables, the player and the enemies. These are the nodes we just added. And then inside of a ready function, we're going to go ahead and randomize. This is an internal thing within the engine that basically makes sure the randomization is getting randomized whenever I call this function. Now, this start wave function that will literally just start the wave. Now, for this, we'll basically for loop through our scenes in the wave list, and spawn our scene. Obviously, none of this will make sense because we don't have this. So, let's create our spawn first. The spawn is pretty simple. We'll pass through a packed scene, which we have up here. We'll add a child, set its position, and it's defeated. Connect to the enemy defeated and say alive plus one. This basically keeps track of how many things are alive in the room. Random spawn position sounds easy enough, but what if the enemy appears right on top of us? Random doesn't know that it's a bad place. So, we'll try a position, check its distance, and reject it if it's too close. And then we'll just keep doing that until we have a good position. We'll limit the attempts as well, though. If one if the room can't give us a valid point, we don't want the game to basically get stuck forever or even stuck for 5 seconds. That's a long time for the player to wait. For this temporary rectangle room, the fallback picks a distance corner instead. That only checks distance. It doesn't tell us whether a wall or obstacle is there. We'll add checks against the actual dungeon later, though. Distance squared works for comparing which point is further without calculating the square root. Now, before we fix the wave list, we'll go ahead and add another function, spawn random point. This basically allows us to take a random point and spawn in the room. Now, the thing is, we don't want to spawn on top of the player because that creates a lot of issues. So, there's a couple things we're going to do to make sure we don't do that. First, we'll get the room, which we'll replace in it with a real room in chapter four, and we'll take attempt in 12 and say variable P is a random range between basically the end and the start, and if the player is null or if the player distance two from P to the player, then we is greater than 120, then we'll return P. That means it's a good attempt. And that means that the position is good. That means we're not on the player and we're not even close to the player. We are 120 pixels away from the player. Once we do that, we'll get the corners, set our set our variable best, for loop P vectors in the corners, and get P.distance squared to the position of the player, see if it's bigger than the distance of the Uh sorry, the best. dot distance squared to the global position. So, basically the same thing, but we're comparing the P and best. And if best is equal to P, then we'll return best. So, we're basically looking for the best position. Okay. Two other things we'll add here is on enemy defeated and clear active room. This also gets rid of our previous problem over here. Before we type the wave list, here's what it's doing. Depth is how far into the dungeon that we are. For now, we always pass in one. And later, it'll grow as we go deeper. A for loop over a plain number just repeats that how many times. So, for I in two adds two of something. Clamp I keeps the grunt to count between three and seven. And int of depth divided by three throws away the fraction. So, an extra caster only shows up once depth reaches three. Brutes don't join until depth two. So, at depth one, this wave is three grunts, a caster, and a charger, and two scatterlings. Once I've gone ahead and done that, I also want to add our wave list function. Now, this one will basically take our list or we're going to make a list first that's empty, and we're going to add in grunt scene, cast scene, charger scene, and scatter scene, and of course, brute. So, we're basically just adding everything that we have at the top. All right. So, let's go ahead and close this and hit play and see what happens. All right. Let's not hit play. Let's actually hit this little guy over here, run current scene. Ooh. And now, on the ready, we already have a bunch of monsters that entered our game. And they're there they are. They're all attacking me already. And this is quite a bit of stuff happening, so I'm kind of got to make sure I kill them before I die. All right, but that's it. Now obviously there's a really big problem, which is once I kill them, nothing will really happen. And if you play for 30 seconds, then all that happens is in the console things will happen, but that's kind of it. But how does the player know when a fight starts or ends? That's another question. Each enemy fades in over a warning ring and can't move until it's fully appeared. So nothing just pops in beside us and gives the player an opportunity to react. When the last enemy dies, the room will show a room cleared message and play a sound and slow the game a little bit for a moment. During the fight, the HUD on our screen information display shows our health and whether our dash, a short burst of movement, is ready. We need to see those while choosing when to dodge or moving for a hit. Now we want to go ahead and open up enemy_base.gd. And at the very top, we're going to go ahead and add two different variables. A spawning that's equal to false by default and base sprite scale is equal to one. This is basically going to allow us to spawn in our monster but with a cool little effect. At the very bottom, we're going to go ahead and add a new function called spawn in. Here we're going to set spawning to true, get our world, which is going to say equal to get_tree.current_scene. We're going to set off the ring and impact with with the juice that we created from before. We're going to say variable keep is equal to sprite.modulate. Sprite.scale is equal to base sprite scale * 0.1. We're going to get our sprite modulate equal to color.r.g. b, which is just RGB. And then we're going to create a tween. So this is the cool part is we're going to basically take our scale from the base scale and set it to 0.3 with set_trans_trans_back and set ease_ease_out. We'll also tween the property spice modulate to keep A 2.05 or sorry, at a at a rate of 0.5 2.5. And then of course, we'll also set spawning back equal to false at the very end. Staying inside of our enemy base, inside of our physics process, right after checking for our state, we're going to go ahead and see if spawning, then we'll set our velocity equal to vector.0. We'll then move and slide and return immediately. And then right after we have the null check, so this will happen right before that. Now, back in our room controller in the spawn function, at the very bottom, we're going to check to see if E has method spawn in, then we will say E spawn in. Now, we want to go ahead and open up the game manager script, and in here, we want to go ahead and add our HUD and player. Once we've done that, we need two new functions that will actually use those, register HUD and register player. We're also going to create a new function called slow mo. It's very similar to hit stop, but it's just slowing down the game rather than completely stopping it. You can actually compare and it's pretty much the same, but we're just using a scale value, which we pass through in the slow mo. Now, we also want to close this and head over to the player and make sure inside of our ready script, we say game.manager.register_player. My boss knows which attack it chose and which phase of that its attack is in. Those are separate questions, though. For the volley, we divide a full turn into evenly spaced directions and spawn a shot at each one. Below the health threshold, some attack values should change, but a separate flag keeps the in-range effect from repeating. Now, the room counts the enemy we've spawned and subtract each defeat. What if one enemy reports defeat twice, though? The remaining count becomes wrong. So, that earlier dead check matters here, too. Test each boss pattern by itself. Then, check that the room counts each enemy once. That way, we know which part to inspect if the encounter ends too early. The camera moves around the world, but we want the health bar to stay in the corner on the screen. So, we'll put the HUD on a canvas layer and use control nodes for its layout. It reads the player's health and cool down values. For a bar, we'll take the ratio from 0 to 1 and multiply its width by the amount, then delay the damage bar. The delayed damage bar uses another displayed value that catches up after a hit. Health still changes immediately, though. We're delaying part of the display, so the player can see how much that they just lost. Now, we obviously need a HUD, so let's go ahead and create a couple new things. Let's create a new script first called hud.gd. We'll go ahead and open that up, but first, let's create our scene, which we will have a canvas layer as the base. This basically is almost like it what it sounds. It's a layer that acts as a canvas on top of everything. I'm going to go ahead and save this as hud.tscn. We're going to add two new things. A control. We're going to duplicate that, and then I'm going to go ahead and add a label. Now, the label needs to be a child of canvas layer. I'm going to rename it the first one to health bar, the second one will be dash bar, and the last one will be the status label. You can go ahead and move these around just a little bit, so that way we don't have them all on top of each other. But, don't worry too much about this. We will come back to this. Let's head over to our script now, and the very first thing we need to do is extend canvas layer because by default, when we created the script it doesn't do that. Next up, we'll go ahead and add all the nodes that I just added. And we're going to get an error here. So, we're actually going to delete that for now because we will fix that in a bit, but for now I'm going to go ahead and delete those. We'll also get our player and our status token. The first thing we want to do before we forget is to register our HUD in our game manager and then set our status label dot visible equal to false. Next up, we want to get access to our player which we can do by saying if it's not valid then we'll set it to or get the first node in group player. We'll also set a ratio between inside of our health bar and dash bar which will matter a little bit more in a bit because we haven't actually made anything for these two health bar and dash bar. But before we move on and do that, let's go ahead and add our last function here, show status. Status token at plus equals one. We're going to take our variable token and set it equal to the status token and we're going to set now we're going to set our status label dot text equal to the text that we want inside of the show layout show status. And we'll have auto hide if it's bigger than zero then we'll create a timer and once it times out then we'll set it back to false. We can draw the health bar as a rectangle, but once health changes how does that rectangle know that it needs to get smaller? There's a couple of solutions here, but this is what we'll do. We'll put the drawing commands in the draw function and use queue redraw when the display changes. Godot then runs drawing function for us. We'll draw the background first and the delayed damage bar and the current fill. Also, check that the current control has a size because a bar with zero width won't really show anything. For the delayed bar we'll use the same time based smoothing as the camera. One minus the exponential of a negative speed times delta. Okay, now we want to go ahead and create our stat bar, which we were having a problem with earlier, which cuz we didn't create it. So, I'm going to go ahead and add this into our scripts folder here, called stat bar. Hit create. And in here, inside the top, I'm going to go ahead and say class name stat bar and extend control. We'll have a few variables here. We're going to export the fill color, ghost color, ghost lerp, and show ghost. We'll also have ratio and {underscore} ghost. We'll create a function here called set ratio. This will basically just allow us to set the ratio with our ghost. It basically heals, snapping up. That way, there's no lag. Next up, we'll have the function process, where we'll say if get tree {dot} paused, then just return. If ghost is bigger than ratio, then we'll set the ghost to a lerp float with ghost and ratio, and then 1.0 divided by the exponential of negative ghost lerp times delta. Now, the important part is to actually draw our UI. Now, there's a lot of ways we can draw UI. This is basically just a way of drawing it with built-in functions, and we can do this by calling {underscore} draw. This is a built-in function that we'll use and basically override and use other built-in functions called draw rectangle. This literally sounds like what it is. We're going to draw a rectangle with this one right here. So, we're going to take this rectangle and draw the rectangle that we want. Now, the size is the built-in size that we'll use in just a minute. So, we're going to have to set that. But, the idea here is that we show ghost, and we'll draw the rectangle here. Oops, on this line. Uh if Well, not if not, but we'll also draw this line as well with fill color. So, this is the ghost color, and this is the fill color. All right. Now, back inside of our room controller, we're going to go ahead and say clear active room and set the status of our room to room cleared with 1.5. I realize we already have this, but we just didn't do anything. So, let's actually just delete this one right here. And then set status, we don't have that, so we need to go ahead and create that. Set status with text and auto hide. We'll basically just say if the game HUD and if the game HUD has method show status, then we'll show the status with our text and auto hide. All right, let's close all this and take a look at what we have. All right, I need to make sure I launch this here. I also need to make sure I actually add this HUD inside of this scene. All right, and we don't really have much going on, so let's take a look at why. So, why isn't the HUD showing? The health and dash bars are control nodes and a control starts with no size. So, a bar with zero width will just draw nothing. So, we give each bar a width and a height. There's one more missing connection, though. The room controller looks for a node called player with a capital P, but in the room it's called player with a lowercase P. So, the spawn check can't find us. It can't find the player. And an enemy could appear right on top of us. Node paths have to match exactly. So, we fix that path. Now, the bars show up during the fight. Okay, what if this room had two waves? Try spawning the second after we defeat the first. Now, the question is when should the room actually count as cleared? Give yourself about 15 minutes to try this out. Check that the room count stays correct and that new enemies don't appear right on the player without warning. You'll need to remember which wave that we're on. When the count reaches zero, either start the next wave or clear the room if it was the last one. If we clear first and then spawn again, the room state will be wrong. Test a full encounter and check that the room clear response happens once after the final defeat. Okay, the room can finish a fight now. Before we multiply that setup across a dungeon, let's check the paths, the projectiles, and the warnings in this one room. We could keep going and generate more rooms, but if this one still has a missing reference, we'd just be carrying that problem forward. So, let's run this room by itself first. These demonstrations use a corrected copy, so compare the setup with your project. Room controller needs the player and enemy nodes, and those paths need to match the names and capitalization in the tree. So, we can run the scene with F6. If a reference is missing, fix that first. The damage function can't update the right object if we haven't connected it to that object. We move the mouse and attack on the same frame. So, which direction should the sword use? The new one. So, we'll update the aim before checking attack input, then update dash. We'll also check the actual move and slide call during hit stop. Stopping a timer somewhere else doesn't really stop that call from running. Follow the order through the function and make sure that the movement check is where the body gets moved. Game manager needs to know which player, camera, and HUD that we're using. We already have ready functions in those scripts. So, add the registration calls there. We don't need a second ready function for this. Then call the Then check that the HUD uses the player's health component and its child path matches the scene. If it If health changes in the debugger, but the bar doesn't, we can focus on the HUD connection and drawing instead of changing the damage calculation. Okay, the caster scene looks right, but is it using the right caster script? Check that first. Then fire just one projectile so we can follow what happens to it. It needs a texture that we can see, a collision shape, a layer the player's hurt box checks, and a wall mask that includes the world. Test a hit and miss separately. It should disappear on contact and its lifetime should remove it if it doesn't hit anything. This is all basically just debugging stuff. >> Okay, the flash works on a normal sprite, but what happens when the sprite is tinted or the sprite is fading? We need to keep those colors in the shader as well. So, we'll pass the vertex color into the fragment stage and combine it with the texture sample. Use the texture once in this calculation. If we multiply an already textured color by the texture again, it changes the result, especially at transparent edges. We'll test a tinted enemy and a fading enemy as well as the normal white sprite. A slam needs a round warning, but a charge needs to show a path. One stretch texture won't really suit both. So, we'll keep a circle and a rectangle and choose the one that the attack needs. Now, we also save the sprite's starting scale here. The spawn animation grows each enemy back to that saved size. So, our bot big boss doesn't end up a normal size. For the circle, the radial gradient stays opaque through most of the shape and fades near the edge. For the rectangle though, we can stretch it and tint a small white image. >> The thing is, the warning tells us where it it's dangerous. So, if the slam hits outside of that circle, we've given the player the wrong information, which is obviously incredibly unfair. We'll match its radius to the hit box. For the charge, we need to show the whole path, including the the body's radius at each end. We'll center that rectangle halfway along the travel. If we only show the destination, a player standing on that path could still be hit outside the warning. So, we'll test around the edges and compare where the warning ends where with where damage can happen. Several hits can happen together. We want to hear them together, too, though. So, we'll keep a small pool of audio players. >> The for loop checks each one for idle player. When it finds one, break stops the search. If they're all playing, we'll reuse a slot rather than keep creating more players. Modulo wraps the slot index back to zero after the last one. We'll also add the room clear sound to the look up, so its name resolves to a stream. Later, we'll expand this pool, but we can test overlapping hits with this new version right now. Okay, let's put these checks together in one room. We'll set up each situation so we know what we're expecting to happen. Check the health and dash bars, fire a caster bolt, and confirm it hat disappears on contact. Clear the enemies and watch the remaining count reach zero. Then check the bosses enrage change and larger volley. We're setting up these situations deliberately so that we can test each one. If something differs in your project, compare that part script and scene connections before moving on into the dungeon. >> The enemy flashes when we hit it, but its health doesn't change. So, where would you look first? Pause and name two checks before changing the damage value. What we can do is check that the accepted hit caused the intended health component, then inspect the damage amount and any check that rejects it. A flash tells us that the visual function ran, which is good. We still need to check that the health update and which component that the HUD is reading. Once those checks pass in your project, we can build more rooms. First, we need a way to describe their floor and walls with tiles. If we paint a room by hand in the Godot editor, that's fine, at least for one room. But it's the same room in every run, so do we really need to do that? So, the code needs a way to describe the room before it draws anything. So, first we decide which squares on the grid are floors. Those floor cells start as a list of positions with nothing drawn yet. Now, the tile set, which is the set of tiles that we need to paint with, gets built in the code as well. So, the whole room is set up as one place. Now, one made in the editor would also work here. Okay, let's say we change the floor from a rectangle to an L. Do we have to move every wall by hand? Well, we already know which cells are floors. We can look around them and collect the neighboring cells that aren't floors. Those give us the border. Then we paint the tiles and build the wall collisions from those positions. So, changing the floor changes where the walls will go as well. We still need to walk around the corners and through any narrow gaps to check if the player fits. We want this floor tile over here to be in the room. But, which position are we talking about? Where the picture is on the image sheet or where we're putting it in the game? We need both. And they're different coordinates. Tile's coordinates chooses which picture we use. Map coordinate chooses the grid cell where we place it. World coordinates are positions in the actual game that is running. So, one floor picture can be used at a lots of different map cells. The tile set describes available tiles, while the tile map layer stores their placement. We'll create these in code, though. For grid positions, we'll use Vector2I, which stores whole numbers rather than fractional coordinates. So, our first step that we want to do is create a new script called dungeon.gd. Inside of here, this is where we'll be actually creating the tile map and everything. So, first step, open up the script. And this is our very first step of procedural generation. The first thing we want to do is see how big the tiles are. Now, I already know beforehand that they're 16 by 16. We'll also preload the tile map packed. This you can take a look at it, but it's basically just the entire tile map. You can see we have multiple ones. Uh we have cursor tile map, mini map, etc. The one we'll be using is the dungeon one. So, you can see here that here it is. And the important thing to note is that basically there's a coordinate for every single tile in this tile map. That's the important part to know. We'll have the floor and the wall. These are basically two different coordinates that we'll keep track of. The source ID and the floor as a dictionary. In the ready function, we'll go ahead and call build a tile set. Obviously, we don't have that yet, so let's go ahead and add that. All right, inside of this function, we're going to go ahead and create a new tile set. This is different than the tile map layer. This is the equivalent of as if I were to add a tile map, went over here and created a new tile set. So, think of it as if in code I've just done this. I'm going back into the code, we're going to go ahead and edit that tile set. We're going to take its tile size and set it to tile times tile. Again, this is basically just how big the size of the tile is. So, the tile size right here is by default 16 by 16, but we're going to make sure it's equal to tile just in case you have something else or a different tile set that you're using. Now, we're going to create a new atlas source. We're going to take that source, set the texture equal to the atlas, which is the pack that we just have here. We're going to have that texture region size again by tile by tile or tile Yeah, tile by tile. Sounds funny when I say it. This is the equivalent again as if I just dragged this in. This is basically as if I just made that uh this tile set. Now, I'm going to go ahead and just delete all this. Going back into my script, we're going to finish up what we were doing and basically for loop C in the floor of the wall plus the floor _deco, then we'll say source.create_tile with C with source ID equal to the tile set. add_source with the source, we'll say tile set is equal to tile set. Now, for the floor decorations, this Oops. is going to be an array of different things. So, 1 4, 2 4, and 3 4. Now, what does any of this mean? Well, let's go back and actually Let me bring back the tile map. And if I look at this and I go to my tile set here and I hover these, you will see the Atlas coordinates of these things. You will see 0 2 0 1 2 1 1 1 You'll see 1 4 which we're using and so forth. 2 4 3 4 and of course 0 4. Those are basically the coordinates that we're using. So these coordinates or these vector I, they're more so essentially coordinates on the tile set or tile map that we're actually using. We could just start painting the floor with floor tiles, but later when we place walls or props, how do we know where the floor is? So let's keep the cell coordinates in a dictionary first. If a coordinate is there in there, it's a floor. Basically, we're using the dictionary as a set. To fill a rectangle, we'll put one loop inside another and go through its columns and rows. The rectangle's end is its starting position plus its size. Range stops before that end point. So we don't add an extra row or column. Then the drawing and collision code can both use the same floor data. Okay, once we've done that, we want to create a new function here called generate. Basically, we're just going to clear first. We're going to take floor {dot} clear and just clear everything before we actually add anything else. Once we've done that, we're going to draw a rectangle here. We're going to for loop through the rectangle's position {dot} x and the rectangle's end {dot} x and then for loop again for the y and then floor, we're going to fill it out x and y equal to true. And then we're going to do underscore paint. We can see health and dash readiness in the HUD now, but those bars only make sense if the HUD is reading the right player and component. We check those references the enemy scripts, projectile contacts, and warning shapes before adding more rooms. Now we're describing the floor with tile data. Which tile picture do we want to use? That's called an atlas coordinate. Where do we put it in the grid? That's a map coordinate. Where is something in the running game? Well, that's a world position. Keeping those separate matters because the number isn't interchangeable at all. We record the floor cells first and now we can use that same record to work out where the border should go. Okay, now we have floor cells. So, where should the walls go? Well, look beside each floor cell. If the neighbor isn't also a floor, that gives us a possible border cell to add to the wall list. We'll store those positions as dictionary keys so the same wall cell doesn't get added several times. Now underscore paint is where we actually paint and derive the walls. This function we're going to go ahead and for loop cell in floor floor.keys set cell Now this is basically just filling it in. So, set cell is a built-in function inside of the tile map layer where this is basically going to draw or paint the cell that we want. The wall set is a dictionary, so we'll have cell for loop So, basically another for loop. It might be a little confusing with the wording here. Uh that actually may might be my bad. I should have changed that, but this is another for loop inside of the floor keys. So, same thing, but we're going to for loop three different times until we do variable n is equal to the cell plus vector 2i with a dx and dy. This basically just creates the wall of eight different neighbors. And then again, we're going to set the cell of the source IDs with the wall. So, this is basically for the floor and then this is for the walls. And that's basically it. So, we're just painting in the floors and the walls now. Okay, now back inside of our room controller we want to call this room floor layer.generate. However, there's a couple problems which is that it just doesn't exist. So, what we'll do is close this first. In this tile map, I'm going to go ahead and delete that tile set. And since we already have this tile map, I'm going to go ahead and rename it to floor. I'm going to add the dungeon dot GD script we just created. Add that inside of here. And I'm actually going to right-click and instead of a tile map, we're going to use a tile map layer. So, because that is two different things, I have another video on my channel uh talking about the differences um And it basically just splits up the tile map into different layers. So, it's a pretty neat addition. It helps you stay organized. Okay, once we've done that, um inside of our I'm going to actually control X on this and move this to the combat room because I realized I've been adding it to the wrong thing this entire time. Once I've done that, back inside of the combat room, we can now drop this in, but rename it to floor layer. And once we've done that, everything should be good. And now let's hit play on the run current scene. And we have a room. It seems to work. Uh there's obviously a very big problem which is the layering is on top of everything. We show up on uh below it. And there's no collision, which is also a pretty big problem cuz if I'm playing my game, then I should want to collide with the walls. Um also, the monsters shouldn't be able to run through the walls. So, there's a lot of issues here. But so far, it's pretty good. Imagine walking down the room and suddenly the floor gets drawn over the player. We don't want the ground changing the order with us. So, we'll give it a lower Z index to keep it behind the character. Then the props can use Y sorting. So, walking behind a rock or in front of it changes which one gets drawn on top. Now we can see walls. Can we walk through them though? That depends on collision. A tile set can include it, but here we're building separate wall shapes from our wall cell data. Either way, painting a picture alone doesn't establish the collision that we need. Run against the boundary and check the physical results. Okay. Now inside of our build tile set function from our dungeon.gd script, right below source create tile, this is where we're going to take our data. Get tile data. And we're going to say if data, then we'll set its Z index to -10. This basically fixes our problem having it in front of everything. Now it'll actually be behind everything. Let's close and give it a try. There we go. Now we're in front of everything. This should guarantee that we're always going to be behind everything. Or sorry, the tile set will always be behind everything. But yeah. Now let's actually make this a real wall because right now the walls don't actually do anything. There's no collision. Inside of our generate function, we're going to check here if instance is valid walls, we're going to queue free. Now walls we don't have, so we need to add that outside of that function. I'm going to go ahead and add it right here. With these uh different variables. And going back down, we're going to go ahead and now we're going to create the walls. This will be done by simply saying walls.staticbody.new. Giving it a name, collision layer, add mask, and wall. Or add child to the wall. Now we also will need another function here called build wall collision. This will take our wall set. We'll for loop through the wall set of keys. And we'll basically create a shape collision shape, a rectangle with a rectangle shape, and set it with tile by tile, so 16 by 16. Get its shape. shape and make it equal to the rectangle that we just created and its size. So basically we're just creating a collision shape with the rectangle for every single wall and setting its position on top of every single tile that we have. And then, of course, we'll add that child walls.add_child(shape). So, basically, what we've done here is we've created one static body. Yeah, let me actually show you as if we were to do this Oops, I just realized I messed that up. There we go. At in nodes. So, I've essentially created one static body, taken a collision shape, I've duplicated this a bunch of times. Let's say we have 16 walls or whatever, and they all have their own position. I'm not going to set each one manually, uh but then we basically went through each collision shape and created a new rectangle shape and went inside of here and set the size 16 by 16 and done that so many different times for every single wall. And then, you can imagine if I do this every single time, we will just have a solid wall. So, let me just delete this. So, hopefully that makes sense. Once we've done that, at the end of generate, I want to go ahead and call that function right after paint, actually. I will just quickly mention that a few hundred collision shapes may seem like a lot, but it's completely fine in this scale because the game is not that big yet, and we never really intend to make the game that big and have so many different collision shapes. A game like this should never have that many. Um if you do want to create the game to have more, um obviously, then that would be something you have to think about. Uh now, also, I am realizing we need to actually put this at the end of the paint function. So, we'll actually put it right here. There we go. So, wall set is over here, so that's where we actually need to add the Let's give each floor cell a 6% chance of getting a decoration. So, do 100 cells always give us six decorations? Well, no. That's not exactly how percentage works. Each cell gets its own role. We might get more, we might get fewer. That's fine for the variation that we want here. If we needed an exact amount, we could just shuffle a list of eligible cells and take a set number from it instead. We're also replacing the tile in that cell on this layer rather than adding a second tile over the first one. Okay, now going back, if you remember, we added the floor D deco or decoration, basically. Um and the the problem is right now is if I play, the ground is pretty solid. Like it's if I'm in the middle of the screen, it kind of seems like there's nothing changing, which is kind of a weird thing to look at. So, we'll add some variety using that decoration. What we'll do is scatter floor decoration. We'll for loop the cells and basically get a random float uh if it's less than this number, then we'll set the cell with a random decoration. Now, this will be called right after the paint. Now, the cool part about this is that we're actually taking the cell and we don't have to repaint anything or worry about kind of like painting on top of anything because what happens is the layer if the layer I'm painting on is the exact same, I paint once and if I'm trying to paint again on it, it'll actually just replace the previous cell that was there. So, I this way, I can actually just paint once and then spread the decorations after. Okay, now, let's go ahead and hit play. And now we see some decorations on the floor. That looks a lot better. Um keep in mind that the decoration spread is about 6%. So, essentially, if you actually counted, it should be about 6%. Obviously, 6% is not always guaranteed, but it is just 6% of whatever. Now, if I did this as like 16 and I hit play, you'll see that it'll be a little more common in a bigger room. But, I think six is not bad. Um if you want to do like 10, honestly, that also might be good. But, do keep in mind that it is it is random, so the chances of getting 10% several times is pretty it's there if it happens, right? So, you never know what's going to happen with the computer when it randomly creates a float. All right, but that is it for now. Uh let's actually make sure the collision works. Man, there we go. Now, I'm stuck inside the room. I'm stuck inside You can see there's a monster out here that's stuck outside the room, too. It's kind of funny. Okay, that monster outside the wall isn't a problem with our room. Our enemies still choose where to spawn with the random spawn point function from chapter three. And that function doesn't know these walls exist yet. So, for now, an enemy can land outside, and we might not be able to finish the wave. Now, in lesson 4.4, each fight will spawn its enemies in the room that we walk into. And now, I can actually attack. This is pretty neat. And the charging guy Ooh, that guy had a lot of health. And there we go. Now, obviously, I can't kill that other guy cuz he's outside the room, but there we go. That's our game, and we have progressed quite a bit. We now have a room. What happens to our walls if the floor is an L or a cross instead of a rectangle? Change the floor shape and find out. Give yourself about 10 minutes to do this. Keep the wall generation code the same and check the border around the new floor. Then walk through it, especially in any narrow connections. Okay, you can combine rectangles for an L shape or choose cells within a radius for a rough circle. The wall cast should use the new floor set. If a passage looks open, but we can't fit through it, compare its width and the player's collision shape. A connected set of cells doesn't guarantee enough clearance for the body. We can draw a room now, but if we scatter rocks everywhere, can we still walk through it? Still will Let's give it obstacle placements some rules. Now, if we scatter rocks everywhere on the floor, one can land in front of the exit. A few can also land together and cut off part of the room. So after placing them, what we can do is check where the player can get to. Now our room from last lesson is still one closed box. There's no exit yet. But in the next lesson, we'll join rooms into a floor and every doorway will open in the middle of a wall. So when we place rocks today, we'll plan for those doors. The way from the middle of the room out of the middle of each wall has to stay clear or we'd be blocking the door we're about to add. We can place a boulder randomly, but what if it blocks the doorway? So we need a few placement rules before adding props. We'll keep important lanes clear. Check the space an obstacle takes up and reject positions too close to other obstacles. To place the prop in the middle of a cell, we'll add half the cell cell size to a corner position. The random roll gives us a possible location. We still decide whether that location works though. After placing the props, we'll also check whether the remaining floor is connected. All right, on the very bottom of our dungeon script, we're going to go ahead and open this up. And add a function called decorate random. Here we're going to go ahead and create a random number between 8 and 20. We'll for loop through that, get our cell and place the boulder cell. Now obviously we don't have that function. So why don't we go ahead and create it? This function will go ahead and place boulder where we'll have a sprite new. We'll set the texture to boulder texture. We'll set the position with cell center. We'll set the sprite. scale with 1.7. And then we'll add decor. We'll add child to the decor. We'll create a rectangle as well and add static box with obstacle. data append. Now we just called a bunch of things that we still don't have. So we need to go ahead and create those as well. At the very top, we're going to go ahead and load a couple things that will help us do exactly what I just said. So, the first thing we'll do is load in three different things. Boulder texture, razor texture, and prop scene. Now, prop scene we don't have yet, so we're going to actually have to create that in just a minute. But before we do that, let's go ahead and add some other variables that we need inside of this script, decor, props, and gates. These are basically just different things that we'll add to our game. The gates will be empty for a couple lessons until 4.4, but we might as well add it now since we probably will need it. We'll also add an array of obstacles. This will hold all the obstacles that we actually have, which we'll have to make in just a minute. Let's continue down at the very bottom here. And for the cell center, let's go ahead and add this. This will basically just return the cell x + 0.5 cell y + 0.5 * tile. This basically literally gets us the center of the cell that we need. For the add static box, I'll add that before the place boulder, but basically here we This is what we'll have is the collision shape rectangle shape. We'll set the size and the shape and everything, and then we'll just add the child to the walls. This literally just adds a static shape or static box specifically. Once I've done that, I'm actually going to go ahead and just comment this out for now just so we can hit play and see what happens. Now, right before we actually hit play, we actually do need to add the decorate random rect inside of the generate. Now, once we've done that, go ahead and hit play. All right, we got an error and that is because we're still actually missing one more function we need to add called free helpers. This will literally just free the things that we have and then create new ones. So, as you can see, we'll just for loop through everything, Q free everything, and then add it all through our own static bodies. We'll have walls, decor, props, and gates. Now, you can imagine that this what we just wrote pretty much is this. It's what we just did, but obviously we don't need to do this anymore. We just need to call the free helper function that we just created. So, we'll replace that with the free helpers. Once we've done that and we hit play, we can now see our amazingly beautiful decor that is pretty big. Um it is unfortunately too big for what we want and that's okay. But, as long as we see that it does work. And now we have generated 10 or 15 different obstacles and this is perfect. Now, what we now need to do is improve what we just made because obviously, as you saw, there's a lot of things that don't work in this thing that we just made. In our current generator, we keep a horizontal strip and a vertical strip through the middle clear forming a cross with room to reach the doors. Then we can place rocks around it. That gives us somewhere to fight and a way out. A rock beside our dodge route can make us move another way. In this example, the rock in the corner we never visit doesn't affect the fight at all. Now, if we move that rock beside the route that we're trying to you dodge, and all of a sudden we have to pick another direction. First, we'll add a new function at the bottom. We'll call it placement blocked. And this is basically just going to return true or false and check to see if something is blocked or not already. It's mostly just a helper at the moment. Next up, we're going to write a decorate room function. This function is pretty much what it sounds like. We're going to decorate our room. This is similar to decorate random, so we'll put it right here for now. The idea here is we're going to get the center of our rectangle. We're going to get the prop count, which is going to be a random range between three and six because 10 to 20 is pretty much too much. We also don't want to make the obstacles too annoying. We don't want too many. Like, there's a lot of things with this that we don't want to spam with. So, for example, if our obstacles are going to give loot, then we don't want too many because that's kind of defeating the purpose of making them special. So, three to six is a pretty good number. Then we'll get the cell with the random range between the position X + 1 and the end of X - 2. This prop would block a lane we're keeping clear. So, okay, skip it. But do we want to stop placing every other prop, too? Well, no, just skip this attempt. Let's continue. Break would stop the loop, and return would leave the whole function. We'll conti- We'll use absolute values to measure distance from the center lines without caring which side we're on. Checking either strip with or leaves a clear cross through the room. Some attempts get rejected, so asking for a few number of attempts doesn't guarantee that we'll end up with that many props. Now, for the very first time in this series, we're going to be checking to see if the absolute cell.x - the center.x is less than two or if the y is less than two, we're going to continue. Lastly, we'll check to see if K is less than or equal to two. Otherwise, we'll place a boulder. Otherwise, we'll place a prop. Now, for both of these functions, we already have the place boulder, but for the place prop, it's actually a lot simpler. We simply want to get our prop scene that we don't have yet, and then we'll add child, say prop.add_position is equal to the cell center, and obstacle.append_rectangle cell X times the tile, cell Y times tile with tile and tile. So, this will basically just add our prop scene to the cell that we want. Now, before we go ahead and continue, there's a few things we need to change inside the generate. So, make sure we have clear, floor.clear, free helpers, and on the bottom we have paint, decorate room, because we're not going to decorate random anymore. We're going to decorate the room with the rectangle, and then scatter floor decor. Now, there's one other thing we want to add, which is place braziers. This is a thing that will go on the wall, which is literally a brazier on the wall. So, let's go ahead and add this under the prop thing that we just created. Place brazier. We'll create a sprite 2D, set the texture of that sprite. So, we're essentially creating the brazier inside of this code. So, we're going to add create the brazier, brazier, I don't know how to say it, brazier. Uh we're going to create some particles with it as well, basically setting CPU particles. There's quite a few. We've done this before, but the basic idea is to just have fire, and then we'll add the child with the flame. We'll set the add the flame to the sprite, and the sprite was added to the decor over here. Now, the last thing we'll add before we continue on completely is another helper function, walkable count. This will literally just have us count how many cells in the floor have no obstacles. Now, obviously, we need a another helper function, so I kind of lied. Um that tells us if we have an obstacle at this cell. And it's pretty similar to the placement blocked. It's just literally obstacles at the cell. Okay. Now, the fun part, which is I don't know if you'd call it fun per se, but finally, we can create our destructible prop. We'll go ahead and create a static body 2D as the base. We're going to call this a destructible prop. I'm going to save it as again, destructible prop in our scenes folder. I'm going to go ahead and add a sprite 2D. A collision shape. Our health component, which I'll just rename to health. And then our hurt box component, which I'll also read just rename to hurt box. And then of course, a another collision shape. For the sprite, we're going to use I'm going to regret saying this, 0.67 or 67. God. Okay. In the sprites, we're going to go ahead and drag this right here, the sprite, if you'd like. Okay. Regardless, now let's add a rectangle shape for both of these. I'm going to actually go ahead and copy this rectangle shape and paste it into this one as well. Now, the hurt box I want it to be slightly bigger. So, huh, I'm going to make this unique first and then make it slightly bigger. And there we go. So, why does a barrel get a health node and a hurt box? Because that's how our sword already damages enemies. So, we don't need any new weapon code to break it. But, there's one setting that we skipped. This hurt box still has the default collision layer and mask. So, our sword's hit box never touches it and the barrel can't break. So, select the hurt box, open collision, and set the layer to only five, the enemy hurt box, and the mask to only six, the player hit box. Those are the same two our enemies hurt boxes uses. Once we've done that, I want to go ahead and create a script here for the destructible prop. Add it into our scripts folder, destructible prop, create, open up the scripts, and let's just replace the top with destructible prop and extend it static body 2D. We will get access to our health and our sprite, and we'll set the ready function, which sets the max health to one and our current max current health to one. We'll also connect the break function, which we have to create. This is super simple. It's literally just a break function. When it dies, we'll basically just get the current scene, play the impact, play the enemy death, and queue free. This will queue free the destructible prop as well. Once I've done that, I'm going to go ahead and head back to my dungeon script, and we'll add another function, or actually before I do that, let's uncomment this now, and that should get rid of all our problems. We have floor and walls now. But, a wall picture by itself doesn't stop the player. We also need its collision. Decorations are simpler, though. Each cell gets a chance, so we don't expect the exact same count every time. Rocks are different because they can block where we walk. We reject ones that overlap other obstacles or sit in the same lanes that we're keeping clear. Either center strip needs to stay open so that condition uses or But okay, each rock passed its own check. Does that prove the whole room works? Not really, not yet. Several valid placements could still cut a off part of the floor. Next, we need to check what Next, we need to check what we can reach after all the plot props are placed. We check one floor cell and find more neighbors to explore. Then those neighbors can lead to more cells. So, we don't know the full list at the start. A while loop lets us keep going as long as there's something left to check. We need each pass to remove, work, or discover something new. Otherwise, it can repeat forever and freeze the game. We'll mark cells visited so we don't keep adding the same ones. So, we'll start at the entrance and follow each walkable neighbor. We'll keep a list of cells to explore and remember the ones that we've already visited. So, we don't keep checking the same cells. When the list is empty, we compare how many cells we reached with the total walkable floors. That's flood fill. Our code takes the last entry from the list, which makes it depth first. This tells us about cell connectivity. It doesn't automatically prove a gap is wide enough for the player's collision shape. Once I've done that, I'm going to add another function all floor reachable. This will literally just make sure that every floor is reachable and flood fill from the entrance. Any floor cell that we can't reach is a bug. So, that's exactly what this does. Now, this is kind of where the convolution basically comes into play when we're making procedurally generated games and functions like this are incredibly important because we need things that will help us make sure we don't have bugs and problems. Once we're done all that, we want to create a new variable here. Start. And now, what we'll do is add if not all floor reachable, then we'll free helpers and then paint again. We'll go ahead and close this. And when you hit play, you can now see our different props here. And it is even collidable, which is nice. And then this little other obstacle that is not breakable. And that's pretty much it. All right, the last thing I actually just realized we need to do is add the place brazier, which we never did. So, right here, we will add the place braziers. With the rectangle position.x + 2, with the y - 1, and similarly, end of the rectangle .x - 3 and y - 1. And then once we hit place play, we can now see our braziers. And they actually look pretty decent. Now, are they braziers? Not really, but they work good enough for now. We have an entrance on the left, and one empty floor cell is surrounded by obstacles. Flood fill reaches every other walkable cell. So, is the room okay, or do we need to still or do we still have a problem? Remember, we wanted to a be able to reach every walkable cell. Well, no, that isolated cell isn't in the reached set, even though nothing occupies the cell itself. We'll compare all the walkable cells with the ones that we reached. After that, we still need to test whether the player's collision shape fits enough through the passage. Before the next task, here's a tool for testing generated rooms. Every random room comes from a random starting number called a seed, and the same seed gives us the same rule. So, the same room. Our room controller calls randomize, which picks a new seed each time we press play. That's why every room is different. But, when a room breaks a rule, we want that exact room back. So, right before we generate, get a number with rand, pass it to seed, and print it. If that room fails, put the printed number into seed instead, and we get the same room again. Okay, pick one thing that you don't want the props to do. Turn that into a placement rule. Then, generate 20 rooms and check whether it holds. You could require space around a doorway, or keep a minimum gap between certain props. Give yourself about 15 minutes to do this. Write down what would count as a failure before generating the rooms. Because if you just generate them and don't have any idea of what is going on, then there's no point. For a minimum gap rule, measure the relevant shapes rather than just their center points. For a doorway rule, check every doorway the room actually uses. If one of the 20 layouts fails, keep its seed or screenshot so you can reproduce it. Passing those samples is very useful evidence for the future. And the placement code still needs to enforce the rules for other rules. Okay, we've checked the routes through one room. Now, we need routes between rooms. So, let's decide how the dungeon connects. Okay, now let's say we have one room that works now. Next, we need to connect several rooms into a floor. A run needs us to be able to get from one room to the next. A common way to join them is with corridors. Now, that's a valid design, but a corridor is a floor we walk through just to reach the next fight. Now, in this version, we can use a bigger grid, where each slot holds a whole room. Rooms in neighboring slots will just share a wall. Each new room goes in a free slot beside one that we've already connected, and we carve a doorway through the wall between them. That will keep the walk between fights very short, and not having to walk through some random corridor that serves no purpose. Okay, we can draw 10 rooms, but can the player get between them? We need to decide the connections between the rooms before worrying about the pictures. Draw each room as a point and put up a line between rooms that connect. That's basically our graph. We start with one room, then add another room beside an existing one and connect them. That keeps every new room connected to the entrance. Because each new room gets one connection back. We get a tree with no loops. After that, we'll turn the room positions into floor rectangles and doorways. We still need to check the finished geometry because a connected room plan can have actual doorway blocked by props. And we'll start off by creating different slot w h. We'll also have grid width and height. The rooms are basically going to be 24 tiles by 14 tiles tall. This will basically just allow us to create the rooms in a number that we want. If you ever want to change it, then of course you can in this code right here. If you want to do that now, then obviously now is the time. Near the bottom here, we'll add variable rooms. We'll also add links. This will literally allow us to link the different rooms. Now, this is where the the quote unquote pre procedural generation comes in. Because now we're going to actually start creating the trees, the more fun part of the project. Okay, we want 10 rooms. We can keep trying to add rooms until we have 10, but how do we know which spaces are already taken and which ones we can still use? The visited cells tell us which grid positions are already occupied. The open list contains rooms with space for another connection, and the option list contains the free neighbors of the room that we chose. We also need a dictionary that maps a grid position to its room index. We'll put a limit on attempts so the loop can stop even if it's reached its target. Even if it can't reach its target. Then we'll check how many rooms were created. We shouldn't assume that we got the requested number just because the function finished. First on the very bottom of our script, we're going to go ahead and start a new function called grow tree. This is the tree that we're going to grow or or say that in such a funny way. We're going to grow this tree that is basically going to create the randomization and the entire dungeon that we want. So first we'll start off with all the different variables that we'll need. So we'll have start which is the random grid and W with it. Grid W and grid H. This will give us a remainder between that. So just keep in mind this means remainder. We'll have visited equals start and true. Order, tree links, index, and guard. We'll then create our while loop where if order dot size is less than target and guard is less than 400 then in order to actually add this to this while loop, we'll have guard plus equals one. We're going to create our open cell as an array and as a variable that we're going to make. We're going to for loop twice, once in the order and then twice or another time in four different things. That basically left, right, up, and down which is exactly what we want. We're basically creating rooms up, left, right, and down, right? If the axis less than zero or if it's if the Y is less than zero, if the axis bigger than the grid W, or if the N dot Y is bigger than the grid H, we'll continue. If not visited has N then we'll append C. So the very first loop, we'll append that and then break. That breaks this Oops. We'll break this for loop right here. Now outside of these for loops right here still inside of the while loop, we will add if the open cell is empty, then we'll break. This will break the while loop. We'll also add a from, which will pick a random open cell, and then options. We're going to create a new array here. Then, we're going to do a very similar thing, for loop through left, right, up, and down. Check the same thing, and then we'll continue. So, we're doing basically the exact same thing as we did here. But, this time there is no break, since we're only doing this once. Outside of that for loop, we'll create another variable two, which is going to be a random thing from the options that we just created. We'll then say visited two is going to be equal to true, because this is the first room we're in, index of two is it going to be equal to the size of our order. And then, we're going to append two inside of order. We'll then take our tree links and append the index of from and two. Now, the last part, the most important part, is outside of the while loop, we need to actually return the order and the links. This will return our dictionary, which we just created. It's a pretty long function, but this is where most of the logic actually lives. If you need to take a step to actually understand this code, I very much strongly encourage you to pause the video and try to read through it and understand what is going on. But, the basic idea is we're for looping a couple times, and creating and appending different rooms. We'll randomize things and find different rooms to add to our dictionary. Once we've done that, we want to scroll all the way back up to the top. Now, each room on the floor needs a job. One is where we start, called the entrance. One holds the boss from chapter three, the big fight that ends the floor. Most are going to be normal fights, and a few become reward rooms, a treasure room with a free reward, a shop where we buy one, and an altar where we trade some maximum health for one. We'll list those jobs in an or enum called room type. For now, every room starts as a fight and the reward rooms stay empty until chapter five. And we're going to add an enumerator, which is going to be a room type. Now, this is the important part because this will allow us to place the rooms. Back to the bottom, we're going to create a new function called place rooms. It's pretty simple. We're going to take our rooms and clear it. This will happen every floor, so we do want to make sure we actually clear it. We'll four loops slot in order, so the dictionary we just created will take the rectangle with the slot width and slot height and then we'll append that room with the combat type. And we'll actually place that room in the game. Okay, each room fills a slot minus one tile every side. So, between two neighbors, there are two tiles of walls. And a doorway has to cut through both. First, we'll check whether the two rooms sit side by side or one above the other. For side by side, we find the rows both rooms, the bigger of the two tops and the smaller of the two bottoms. We take the middle of that stretch and carve that row and the one above it. So, the door is just two tiles wide. Rooms above and below work the same way with columns. And we save every carved cell in both rooms because that's where the gates go later. Now, this is cool. We actually have quite a bit so far, but there is another important function, which is to punch the doorways between the different rooms. Now, this one is just going to be a for loop where we link through the tree lengths. We'll create a couple variables here. And this will literally just find where we want to place the door. So, we're going to look for where are we placing the door, whether it's horizontal or it's going to be vertical. Now, obviously we need two different functions that do those two things. So, for the horizontal we will create three different integer variables with a max and min and floor integer. So, the I here, by the way, is just integer in case that wasn't super obvious. And then for the for loop of four loop inside of the range between the left dot end X right position X and we'll set the array of our floor of those positions to true for both. And then we'll record the door as well because we want to keep track of where we actually add the door. And then we'll do the same thing but for the vertical. So, we'll do the pretty much the exact same thing. But you can see the difference is here is Y and then here is X. So, it's pretty much the same thing. Okay. Now, the other last part is the record door function. This one is a little easier. We need to four loop in I between the room sizes and we're going to just check to see if R is equal to A or if R is equal to B. If it is, then we will say rooms dot I at doors.append the cell. This will literally just record the door. That's kind of what the function is. It's recording whether or not we actually have a door there. Okay, before we actually continue, we need to go ahead and remove the start wave from our room controller. So, let's go ahead and delete this. Now, obviously we do keep the generate because this is where inside of here we'll actually call what we just created. So, first right here, we need to go ahead and clear three helpers, rooms.clear and then floor.clear. This will allow us to basically clear everything that we have previously. Now, obviously in the beginning we have nothing, but this will be important when we regenerate things. All right, now for the fun part is how many rooms we're going to create and you know, actually decorating and creating the rooms. >> Then we can replace all this, whoops, all this with creating the slots, basically how many rooms are we going to have? So, seven is a pretty good number. If you want to have this growing, that's actually not a bad idea either. For the moment, we'll just do seven. We'll place the rooms, punch the doorways, we'll have links is equal to the slot of the links. And then paint. Now, this is obviously important for outside this function because we do need to save the links outside of this function. We'll also have a problem with the player spawning because at no point do we ever actually change the player's position. So, I am kind of curious what will happen if we hit play, but um at this point maybe you can try it and see what happens, but just in case because I kind of know what's going to happen is right here inside of the room controller, I'm going to set the player's global position equal to the lower layer. entrance center. Which we don't have at the moment. Uh which I think will error, so let's actually comment that out. And I guess let's find out what happens. Let's hit play. And we can see our dungeon got generated. So, what we can do here is a little little hack. We can actually move our player, and if we go back to our game, we move him enough, he should actually teleport inside the rooms. There we go. And we can see the rooms got have uh are all connected with a door, which is awesome. We can keep exploring, and we can see that we basically have a full dungeon. This is pretty cool. So, we now have a procedurally generated dungeon with seven different rooms, each kind of with its own combat room or different room type, which we haven't actually created yet or set yet. And there's quite a few things we still need to finish, but this is a pretty good point where now we have our player. We don't have any monsters spawning, which is a pretty big problem, which we'll fix in just a minute because we do have room types. So, we need to make sure that we are actually assigning the types properly. Now, we can connect the rooms into a floor in a different way, but we still need somewhere to actually start and a boss that we need to reach. So, which room is the boss? If every room just rolls a random type, sooner or later we'll get a floor with no boss on it, and that run will just not be able to be finished. That's basically a bug that is really problematic. So, we don't leave the things a run needs to be a lucky roll. Now, the starting room will it is always be the entrance. We also need at least one room to always have a normal fight, and the rest can become shops or other reward rooms, such as treasure rooms or altars. Then we generate a bunch of floors and check that everyone has an entrance, a boss, and at least one fight. Where should we put the boss? Well, probably somewhere far from the entrance, cuz having the boss right next to the entrance would be a little weird. But, what does far mean here? A room can look close on screen, but still take five doors to reach. We care about the route here. That's the main idea. So, we'll start at the entrance, check rooms one doorway away, then two doorways away, and just keep going. That's breadth-first search. If you've ever done computer science, then this term might be familiar. A queue keeps that order and will store each room's distance as we reach it. Then we'll use the farthest result when assigning the boss room. We need that last step as well. Adding the helper alone won't change where the boss spawns. The first thing I like to do here in this point would be to assign the furthest room. The reason why this is neat is because what we can do here is create this function farthest room, and it's literally going to do exactly what it sounds like. We're just going to find the furthest room. >> So, the way this works is we're going to basically take distance and we're going to kind of emulate as if I'm walking through the rooms. And every time I find a distance that is bigger than the current distance that I kind of have saved, then I'm going to set that new distance. This is actually a really cool trick um and a very common one. So, this is actually a function I would definitely recommend like sitting on if you don't really understand it. I'll actually give you a chance to read this function first by yourself and we'll continue on. Um but the important part here is that we're going to set or return the farthest room that we can find and this is specifically for the boss. The boss is going to go into this room. We want the special rooms in a different order. So, we'll shuffle the array. But what if another variable refers to that same array? It sees the shuffled order, too. Because we change the array itself. If we need to keep the old order, we'll duplicate it first and shuffle the copy. That normally copies the outer array. Nested arrays or dictionaries can still be shared. So, we need to check those separately. Later, we'll use slice and take part of the list. Its end index isn't included. So, a slice from zero to two contains entries zero and one. Okay. Now, the other important part here is to have assigned types. Here is where we'll actually assign the room types. The first room is going to just be the entrance. This kind of makes sense. Uh and this will actually go into play for this line here, the entrance center. So, going back in the room controller, I'm going to uncomment this. Go back to my dungeon. And in here, this will basically allow us to get the room type being set to treasure, shop, altar, and treasure. We'll also have the boss room or or boss the boss type uh being set as a room. Notice this line, though. The boss still goes in the last room in the list. Nothing calls our farthest room helper yet. That's your turn at the end of this lesson. We'll also have the middle room become special, but we also want to make sure that uh there is at least one room for combat every floor for a very obvious reason, because if we have a floor that is just treasures and etc., that's kind of lame. Um if anything, we might actually want more than one room to be combat, um but in this case, this is totally fine. Now, going back to our generate function, we're going to uh basically complete this function, because at the moment, this function is pretty incomplete. We're going to actually change the function a little bit. We're going to actually replace it with depth. This is going to be basically what floor we're on, and by default, we're always going to start on one, because we're always on floor one when we start the game. We're always going to start with clearing everything, so this can stay. But now, like I said previously, we can actually adjust the slots based on the depth. So, that's actually a pretty cool extra part we can have. These parts are going to be similar, but we're also just going to have assign type. Make sure we actually assign the types of rooms. Then, we will for loop through all our room sizes or through all our rooms, sorry. Dot size, so this is how many rooms we have, we'll for loop through them. And we'll basically check to see if we have a combat or if there's a boss, we'll decorate it with the thing, the function that we created for decorate room. I've got they're called braziers, there we go. Now, if not all floors are reachable, then we'll get the rooms. dot at zero and rect. get center. Read the helper, and then we'll paint and scatter the floor decor again at the very end. This goes outside the if statement. I said that as if it was inside, but it's outside. We know the player's position, so can we just check which room contains it? Well, the player's position is in world coordinates, and our rooms use tile cells. Those numbers aren't measuring the same thing yet. First, we turn the global position into the dungeon's local position. Then, we ask the tile layer which map cell contains it. Now, we can check the cell against the room rectangle. To put an object back in the world, we can do the reverse. Get the local center of the cell, then convert it to the global position. That also handles a dungeon node that's been moved away from the world origin. Okay. Now, finally, couple helper functions that we'll need, especially for the room control we we just wrote. These ones are going to make the most sense, I think. Room at world position. We basically want to find the room that we're at. The way this works is we'll call a built-in two built-in functions, local to map and to local. We'll basically just have the world position as a vector two, find the cell, and then we'll look where that cell is inside of our rooms. Once we find it, then we will return I. If we can't find it, we'll return -1. Now, the fun part is the room center world, and the entrance center, that is exactly what we want for the room controller. And then, the next function we'll have here is random point in room. Here, we're going to get our variable rectangle I, candidate, and then we'll have a nested for loop between our rectangle's position X and rectangle's position Y, basically mapping out the a 2D rectangle, essentially. And then, we'll get 2P, or two global, sorry. I send the cell center of the X and Y that we are for looping in, and then we'll append the candidates. Then, we'll shuffle it. This is basically going to replace the spawn the random spawn point that we kind of have from previous previous lesson. And now, we will have our last function, blocked. This will basically tell us if there is something blocking anything. We'll follow up through the obstacle and we're going to grow say have rectangle. Grow 10. And then if we're going to we're going to check if it has a point. If yes, we'll return true. Otherwise, we'll return false. Okay, now obviously here we call the entrance center. And let's see what happens if I hit play. All right, I got spawned in the middle of this room. That's awesome. That is perfect. Now everything else will continue on in the next room. But you can see here this is a combat because it has braziers. Uh it's either a combat or a boss room. I'm I'm kind of unsure cuz there's nothing spawning. Uh but that's okay. We'll take care of that in the next one. So this one's also a brazier one. You can see the obstacles and everything. And yeah, that's pretty much it. We can have a room that's connected on paper and still can't be walked through. That's why we're checking more than one thing. Flood fill follows walkable neighbors inside the room. The dungeon graph records which rooms connect through the doors. Then we still need to carve those doors and leave enough space for the player's body. Okay, the entrance connects to A. A connects to B and B connects to C. D is drawn further away, but it connects straight to the entrance. So which room takes the most doors to reach? C takes three doors while D only takes one. So we choose C. When looking for the farthest room by connections. Okay, the boss is in the last room that we added. Does that mean it's farthest away from the entrance? Check the actual number of doors it takes to reach each room. Generate 10 floors and compare the assignment with distance from the entrance. If the earlier fix is already in the build, test it rather than adding it twice. Give yourself about 12 minutes to do this. Okay, start at the entrance and count outwards one door at a time. That's what breadth-first search gives us here. We pick a room with the largest count, then actually use that result when assigning the boss. But, what if even the farthest room is only two doorways away? It's still going to be the farthest. If we want a longer trip, we need another rule that checks the layout has one. Now, let's wire it into our project. In assign type, we can ask farthest room for the boss's index and put the boss there, as long as there isn't room zero, which is the entrance. The loop that collects the middle room used to stop one room early because the last room was the boss. Now, the boss can be in any room. So, we loop over every room after the entrance and skip the boss's index. And inside of the assign type function, right below the room zero type equal entrance, we're going to go ahead and get our box index, and we're going to just change this check to see if the box index is not equal zero. And here, we'll simply change this to get the room's boss index with type equal the room type boss. And then similarly in this for loop here, instead of the room sizes, we'll simply just do uh sorry, minus one. We'll simply just remove the minus one, and that's it. And then right here, which we don't have, we'll add an if statement and then append if the I is not equal to the middle or the boss, sorry. We have more connected rooms now. But, entering a room for the first time should be a little different from coming back after clearing it. We need to remember that. Okay, let's say we walk into a fight, take a hit, and just walk straight back out. Is that what we want? For this game, not really. If we can leave whenever we want, the fight is pretty optional, and it doesn't really make it important. So, what we can do is close the gates when we walk in, and open them once the last enemy is defeated. Walking in starts a fight that we have to actually finish now. Okay, but now the room has to know when it's cleared. We count the enemies as they spawn and count down every time one dies. So, what happens if one dies without telling the room though that it died? Well, the gate will stay shut. There are no enemies left, there's nothing we can do. That's basically a soft lock, and it's pretty much the worst bug that a room can have, because the run can't go on now. Now, the player is forced to just alt-F4 or I don't know, restart the run. So, every enemy that we spawn has to tell the room when it dies. And we play the fights through to check the gates open. And with six or more rooms that all look the same inside, it's really easy to get lost. We'll check the player's room repeatedly. But, we only want to start the fight once they enter. So, we'll remember the current room and separately track the active encounter. -1 means that there's no active room in this code. And busy flag stops another transition starting while we're handling one. We'll also wait until the player is inside before closing the gate. Otherwise, we could catch them in the doorway. When the enemies are defeated, we'll mark that room as cleared and open the gates. Coming back into it should keep that cleared state. All right. We are now in our home stretch of completing the dungeon stuff. At least for now. Going back inside of our room controller, we want to add in the ready function, right below the await get tree, enter floor. Now, obviously we have an issue here is that we don't have that function. So, at the very bottom, let's go ahead and create enter floor. Here, we'll literally just enter the floor by generating with the depth. So, as you recall earlier, we now take in a number, and this is how what depth we're actually in. We'll take our current floor and set it equal to -2, and set our player's position inside of the entrance center every time I enter a floor. Now, at the top, we do need some new variables. We'll add current floor, active floor room, and then floor depth. -1 means there's no fight in progress. We'll also have busy, which is a boolean, and then scrolling down, right below, I'll say the ready, that's usually where I add it. We'll add our physics process. And this is where we're going to check to see if busy or if active room not equal one or if the player is not equal to or is equal to null, then we will simply return. Then we'll add a variable here, which is going to get a room at the player's global position. We're basically going to check to see if the player if the player's room is less than zero, and then we'll return if so. Next, we will check to see the floor layer's room here at rectangle. We're basically going to check to see if there is a point player at at the player's position. If there isn't, then we'll simply return. And then lastly, if here is not equal to the current room, then we will set the current room equal to here, and then we will enter room. Now, before we fix this, I want to go ahead and head over to the dungeon script, and we need a couple things in here as well. We're going to need the gate node. So, again, instead of scrolling, I'm going to use this. We have quite a bit of code here. We're going to add a gate node here. This is basically a dictionary, and we're going to add a function at the very bottom, which is basically just going to lock the rooms for us. Here, we're going to say if gate nodes has I, we'll just return, because that means it already exists. We're going to create an array, and then we're going to for loop through our rooms of doors and create a gate, basically. This is basically just creating a gate in front of the room, so that way it's locked. This is specifically for when we actually enter the room, we want to make sure that the room gets locked when I enter the room. Uh we'll Now, obviously, we will also need a function that unlocks the room once we complete it. So, we're going to do basically the same, but obviously, we don't need to create anything. So, we're just going to Q3. We're going to have to find it first, obviously, and then we'll just Q3. That's it. We'll also erase it from the gate nodes. Uh so, it's kind of similar to Q3, but this will erase it from our dictionary. Now, going back to our room controller, this is where we'll uh finish this error here. So, at the very bottom, we're going to go ahead and create a new function, enter room. And this is where we can actually get a bit more fun. We'll enter the room depending on what it is, or we'll kind of start something. So, we'll start combat or start boss. So, this is two different types. Now, the cool part here is obviously, we get to spawn in different monsters or things, and randomize these things. So, here we will start combat. This is the spawn. So, we'll spawn the monsters. Now, for that function, we'll simply pass through our spawn scene. So, it's going to be very similar to our spawn function. As I say that, I realize the name is the same, so I actually do need to delete the old one. So, let's go ahead and actually delete this old one. Now, on top of that, uh we will need to delete the start wave function. And then the spawn uh random point function, we'll need to delete that as well. Okay. Now, going back down to our spawn, it's pretty much the same thing, but we'll just spawn in and we're going to make sure they spawn inside of the room specifically. Now, we also will need the start boss. This one will do a very similar thing, but we're just going to spawn in the boss. So, this one's a little easier because all we need to do is spawn in one boss. Another is a problem, which was we don't have that boss yet. So, at the very top, let's go ahead and add the boss enemy. Scrolling back down, we'll still need another function, function clear active room. This will uh be a replacement for our old one, actually. So, let's go ahead and find the clear active room. So, here we go. We'll actually do a bit more than just printing something. Now, we actually un- unlock the room, we set it as cleared, and there's a few other things we actually do now. Because before, we would just print something, which was not much. So, now we can actually have this stuff, and we can always add more if we want, if we want a victory cheer or something else, that's always doable here. Now, inside of our game manager, now we want one place that counts what happens during a run. The rooms we've cleared, the enemies that we've beaten, and the floor that we're on. When a run ends, the death screen will show these. We'll also leave slots for things that we haven't filled yet. Like gold, which we pick up and spend during a run from chapter five. And essence, a currency that we'll keep between runs. Plus a score and our best combo, from chapter six. For now, only the rooms cleared and the floor will get filled in. Okay, we finish a run and we set our stats to the defaults, but somehow the old score is still there. So, what happened? If the current stats and default both point to the same dictionary, changing one changes the other as well. Duplicate duplicate gives us a separate dictionary. A shallow copy is enough for these simple values. If we add nested arrays or dictionaries later, we'll need to check whether those should be copied, too. For now, the important part is that resetting the run gets fresh values instead of reusing the previous run stats. We want to add a couple new things. We will add the default run states, or stats, sorry. Uh run stats will be be equal to the default.duplicate. So, this is basically duplicating this entire thing, uh and putting that it of this. We'll basically have all the things saved. So, we'll have rooms cleared, enemies killed, essence, gold, score, max combo, started MS, and floor. All right. Now, at this point, let's go ahead, close all that, and hit play. Now, let's see if I can find a combat room. All right, here we go. This was a combat room. And as you can see, the monsters spawned and are hitting me. And I can kill them. Oops. Once you've killed the last one, the room should unlock. And there we go. That is pretty much everything we just did. And it seems to be working pretty nicely. You can see this is the boss. And you can see it's locked me back in the room as well. Okay. All right. Now, one of the parts, obviously, that we may have noticed is the game is kind of hard to navigate without a mini-map. The mini-map is a small overview of the floors that help us see where we are. The code that builds the floor already stores every room and every connection. So, we can use that information to draw the map. We draw a box for each room, colored by its type, and a line for each connection. The room we're standing in pulses, and the fights that we've cleared go dim. We can redraw the mini-map from the generator's room and connection data. So, it matches that the floor we're actually on. We don't need a second copy of the layout that could fall out of sync. So, inside of our HUD here, which I realize is never renamed to HUD. I'm going to go ahead and save that as HUD. Renaming it inside of the combat room as well. Inside of here for that control node that we just added, I'm going to rename it to mini-map. And I'm going to go ahead and add it to the bottom right or the top right that sends tends to be the most common place. I'm going to go ahead and add a script here called mini map. Save it inside of our scripts folder. It create. Now inside of here, we'll go ahead and add a variable dungeon and pulse. We'll add another function called set dungeon which will simply set the dungeon and save basically everything that we create. Because what's going to happen is we want to basically call this kind of script and draw everything after we make the rooms. Once we've done that we'll add another function called room center tiles. We'll basically return the center of the room the dungeon room. And then the important part here is the process. This will allow us to actually draw everything. Now for the draw function, we're going to override the default which is I think makes sense because since we want to create and draw our own custom drawing. First, we'll find the bounds of the whole dungeon. Then we'll shift those coordinates to start at zero and scale them into space that's available in the HUD. We'll use the smaller scale from two axis so the map fits without stretching it. Finally, we'll center it. Draw rectangles for the rooms and draw lines for the connections that we stored. Nearby rooms only get a line if they're actually connected. We'll highlight the current room so we can see where the player is. So we're going to call underscore draw. Now we're going to get the bounds of the whole dungeon in the tile space. We do that by Oops, this is should be right here. We're going to get the min P max P which is just going to be infinite for both uh for positive and then negative. But we'll set that in a minute anyway, so don't worry about it. So here we'll set it the X and Y to the minimum float of the minimum p.x and the r.x position. So, we're basically looking for the rooms and we're just mapping it out essentially. So, we're getting the whole dungeon tile space. Once we've done that, we want to create a few variables here. pad 9.0 area cs or ssc off and then every room box and every connection line needs the same conversion onto the mini map. Subtract the dungeon's smallest corner, scale it down, and add the to offset that centers the map. So, instead of writing that math in several places, we'll keep it in a small function stored in a variable called to map. It's the same kind of unnamed function that we gave between in back in chapter two because it lives in a variable. We run it with dot call and pass the point in. And it gives back where that point lands on the mini map. Here, we will now create a small function here. We'll basically to map will simply return the tile minus the mini map or mini min p, sorry, times the sc plus off. Once I've done that, I'm going to four loop in the dungeon lengths and then I'm going to call the room center of each one and then the fun part is we're going to actually draw the line. This will draw the dungeons across where we want it to be. Then, we will call the game manager.players or see if it exists. If so, we'll set our current dungeon to the dungeon.room at the player's current position. Once I've done that, we now want to actually four loop through everything and draw the rectangles. Now, this is the more fun part is we actually get to draw the rectangles for every room. Now, heading over to the room controller at the very end of the enter floor. So, let's actually just look up enter floor. Here we go. We want to add or basically get our mini map. So, MM for mini map. We're going to find our mini map and call set dungeon at floor layer. So, set dungeon will basically draw the map every time I enter a new map. Now, obviously the color four doesn't exist, so we need to make that. So, we'll go ahead and add that. And this basically just sets the color of the room depending on what type it is. So, if it's a boss, it'll be red, treasure yellow, shop uh green, altar will be purple. Okay, now we can see the whole route. But, having a shop and a treasure room on it doesn't tell us whether they're useful at all. Walk through the floor and check how many fights come before a reward or a break. In our build, shops, treasure rooms, and altars give us rewards between fights. Every normal fight on a floor also uses the same group of enemies. So, each fight can work on its own, while the run still feels the same from one fight to the other. Now, when we beat the boss, we go down to a new floor from the same generator with more rooms and larger groups of enemies. More rooms and enemies alone do not tell us where the run gets harder and where it gets a break. We still need to play the deeper floors and check the fights and rewards along the route. The message needs to say floor one, then floor two, and so forth. We could write a different string for each, but the only thing changing is the number. So, we'll leave a placeholder and put the current floor into it. Percent D for an integer and percent S is for text. The percent operator fills those placeholders. Earlier, we used percent between numbers to calculate a remainder with a format string. It has this other use, though. We'll also use backslash n instead of a string when we want to display the text to start a new line. Now, back inside of our room controller for the enter floor right before we just added everything I we just added, we want to now replace it with all this. So, we're going to run the stats for the floor, set it equal to depth, set alive equal to zero, floor layer.generate with a depth. We're going to set our player's position to the center of that. Get our current room meant equal minus two, active room minus one, and set the status floor whatever is equal to the depth of two point zero. So, this basically is referring to the depth. So, this will always print the number floor X clear floor one cleared, clear the boss room, etc. Now, inside of the clear active room at the very bottom, we want to go ahead and say if the room type is equal to the boss, it will say busy is equal to true. We will await 1.5 seconds, enter floor, and then that's it. So, this basically allows us to enter the next floor, but we're kind of waiting a little bit 1.5 seconds. So, that way there's a bit of breathe room before we kind of just suddenly teleport to the next dungeon. Right, at this point you can go ahead and give it a try. Hit play, and that's not the right one. Hit play in the combat room. So, I realize we do need to add this to the the mini map the to the mini map group cuz we want it to look for the mini map, and I'm going to go ahead and rename it to capital F M. And there we go. We now see our rooms. And you can see they get highlighted as I enter them, and you can see there's no line where there is no room connection. So, there you go. There's our small mini map. And obviously, if you want to make it bigger, you're more than welcome to do that inside of the code inside of here. I do actually encourage you to try making it bigger. Um that way you can tinker around the numbers. So, you're not just copying the code and seeing if it actually works properly. Okay, we've cleared this room, left it, and now we're coming back in. So, the gates close again. Should we get another fight or another reward? Decide what you expect, and take a couple of minutes to try it. It should probably stay clear. We shouldn't spawn the encounter or award the same clear reward again. It kind of defeats the purpose of these kinds of games. If it restarts, check the room's saved clear flag and then check that runs when we enter. An enemy count of zero by itself doesn't tell us whether this room has actually been finished though. Okay, what would you change about the rooms that we visit on a floor? Pick one rule that you want to add. For example, requiring a treasure room or limit how many early particular room types that can appear. Give yourself about 15 minutes to plan this out, generate 10 rooms, and then check each one. Explain what the rule changes for the player, not only what shape it will produce. Okay, if we require treasure, we'll reserve a valid room for it instead of just hoping a random assignment produces one. If a room must appear farther away from the entrance, we'll check graph distance. Choose a rule the current layout can satisfy and handle a layout that's too small. Then test the actual route to see whether it creates the change that you intended. Okay, now look at how much this one room depends on. We need a player, attacks, enemies, and something that it knows when the fight is over. If you're learning these things from a separate tutorial, figuring out how they connect can become another project on its own. You can finish a movement tutorial, find an enemy tutorial, and suddenly they're making different assumptions about how your game works. If you even take this entire course and then try to add other things from different tutorials, you might run into that exact same problem. You'll basically just have a hard time understanding what is going on. And believe it or not, the same thing will happen with AI. Now, that's one of the things that I wanted Coding Quest to help with. On the website, a campaign gives you a path towards a game. It's broken into quests, and each quest works through a system that contributes to that project. But each one is made in such a way that you can take it and understand it and learn from it, and then be able to add anything that you actually want to your own game. Now, the roguelike path starts with controlling the player, then moves through combat, enemies, rooms, and the rest of the run. So, when you finish a piece, there's a next step that has a reason to be there. Inside the quest, you're writing the code yourself, as well. You're not just copy-pasting what I put on screen. There's also checks on the attempts that check to see if you're doing things correctly or not. You can use the course to understand the bigger decisions, then use a quest to practice working through one of the systems. Now, if this project is a bit ahead of where you are, and you find the difficulty of this quest a little too high, the site's start here page helps you find your exact starting point. If you have absolutely no experience, then it'll guide you to where you should be. You don't have to jump into the whole roguelike immediately. Now, there are free quests that you can try, as well. The guild hall is the paid membership for continuing through the full campaigns. Have a look at coding quest using the link down below, pick a starting point, and try the first task. Getting started is completely free, so go give it a try. Give yourself something small to finish and actually test. There's also a 7-day free trial, so you don't even have to commit to it. Room encounters are working. Now, let's look at what we can see and hear during one. Especially when several things happen together. Okay, our dungeon works now. We generate a floor, the gate locks, we're going to start fights, and we can fight our way to the boss. But when we play it, it still kind of feels flat. Hits kind of sound thin. Enemies vanish the moment they die, and every room is lit the same. So, in this lesson, we're not adding new features. We're going to be switching on things that we've already built. Basically, improving everything. First, we'll make sure that the game runs on a real dungeon scene. Then, the player needs a health variable because, well, HUD reads the player's health, and the player script never stored its health node in one. After that, we'll let sounds overlap. Give enemies a proper death, light up the room, and pull the camera back so we can see attacks coming a little bit. Okay, now before we move on, there's a small trick I want to mention, which is when we actually hit play, it's kind of launching our wrong scene here, and that is the main scene. Now, there's a lot of ways we can change this, but one of the easiest ways is if we find the combat room and right-click it, we can go ahead and set as main scene. This will immediately change this to a blue color and the main is no longer highlighted. And if we hit play, it'll show up as our main game now. Okay, now that we have the combat room playing as the main thing, there's a couple things that we want to fix. First being inside of our player, I want to go ahead and load the health by adding an on-ready variable for the health. Now, another issue is in the audio, we have every single sound that we have playing canceling the previous audio. So, it was something that wasn't super easy to realize, but if you really paid attention to it, it could be there, and it's kind of annoying if you actually listen to it. Okay, one swing hits three enemies. We ask for the three hit sounds, but if they all use the same audio stream player, each one can replace the last. So, how do we let them overlap? We'll keep a pool of players. We made a smaller version earlier, but now we use but now we'll use 16 and cycle through them. That's still a limit. Once they are busy, another sound can replace one that's playing. We'll also choose sound variants and adjust pitch. In this function, a positive pitch argument uses the value that we passed in. The random variation runs in the other branch. So, passing a fixed positive pitch means that we won't get the variation. The first thing we'll do is add a constant pool size, which will be 16. Then, we're going to go ahead and expand our sound size, our essentially the pool of sounds that we have. I'm going to go ahead and load all these in. Now, keep in mind that there's going to be libraries or arrays of different types of hits. Once I've done that, I'm going to add a constant variation, which will allow us to numerize essentially the slash hit, things like that. We'll also add or replace a player with players, next, and streams. Now, because we don't have player anymore, what we're going to actually do here is First, we're going to set our process mode to always. This will allow us to always have the music or a sound playing, even if the game is paused, which can be important if I'm playing music. Next up, we'll create an audio stream player for every pool size, meaning 16. Now, we need to preload the sound streams, which we can do by going to the bottom and adding a preload streams function. We'll for loop through the sounds, create another array loaded, and we're basically going to see if the resource loader exist at the audio direction. And this basically preloads everything. So, that's kind of what we were doing before here, but now we're just doing this in a function in the ready function. Now, obviously, the right the play function is going to change a little bit. And what we can do here is the variations will load it in by saying streams.get. I'll mostly load them in. And we'll basically just have everything else pretty similar. We'll just have the volume, stream, and pitch. We'll change that depending on what we want with a random range, and then we'll play it. We'll also have a default for these, that way nothing before when I played audio will change, unless I actually want it to. Okay, another small fix that we're going to add here is it's not really a bug per se, but inside of our hurt box if you were following along what I was doing, I added a print function at some point and it is good practice to just delete that because that was from a couple lessons ago and it's kind of just stuck there for absolutely no reason. Well, I'm going to go ahead and delete it. Now, when you hit play and you try listening to the game itself, you'll notice that it sounds a little bit better and just less annoying. Now, another thing here is it's not really a bug, but we're going to fix this Q free right here. That is the weak steep monster immediately. It's as if there was no big feedback, like nothing actually happened. So, we do have the death enemy, but that's not enough. The enemy dies and we fade the sprite out, but during that fade, can we can it still attack? Can we attack it? Can another effect still choose it as a target? We need to mark it as dead and stop its gameplay immediately even while the picture is still there. That in between can finish the fade before we queue the node for deletion. That means an enemy can still exist in the scene while it's already dead. Later, when we look for chain lightning targets checking that the node exists won't be enough. We'll need to check its dead state as well so we don't hit an enemy that's only waiting for its fade to finish. So, what we'll do here is we're going to add a few different things. Right below the velocities is to zero I'm going to go ahead and disable the attack area. I'm going to hide the telegraph. We're going to get our hurt back and set deferred monitoring to false. We'll also set deferred collision layer to zero. Now, this is also important because if you were paying attention and kind of playing the game on your own, you might have noticed that you could still collide with it. It might have been a fraction of a second, but you could still collide with the monster as it's dying. And that's because there's that small area where before we destroy it, it's still collidable. After we defeat the emit or get the emit to defeat, we're also going to create or get access to our scene. And then the fun part is we're going to start creating some juice. So, we're going to say juice flash, sprite color white. We'll impact in the world with the global position of our self, so the monster, with the color red and 12 and 1.4. We'll also do ring. We'll create a ring around our monster. And then lastly, we'll also set outline with the sprite false. Okay. Now, for the actual fade, basically, is we're going to create a tween for this. So, we'll create a tween and then set parallel. And then in that tween, whoops, we're going to tween the property of scale. And then we're also going to treat set tween the modulate A to zero over a time of 0.28 for both of these. And now for the Q free is we can pretty much delete that because we'll just get our chain and tween callback Q free. So, this will basically Q free once this tween is done. So, now the death animation kind of looks like an animation. So, this basically gives the monster a proper death. Okay, we enter a room, close the gates, start a fight. Good. Once it's cleared, coming back should leave it cleared. So, the controller remembers more than just how many enemies are alive right now. It tracks the current room, the active fights, and whether that room has already finished. The mini-map shows those same rooms and connections at a smaller scale. World also lets sounds overlap and made enemies fade when they die. But, during that fade, the node still exists. Does that mean it's a valid target? No, it's already dead. Any effect that searches for enemies needs to check that as well. So, we'll need this again when attacks start jumping between nearby targets. Okay, now closing this. We also have a small issue inside of our combat room, which is that it feels kind of dead. Like, the scenes don't really feel alive. There's nothing here. We want the room darker with light around things like braziers. So, first we'll darken the room with canvas modulate. Then, add lights where we want to use more. Point light 2D uses a texture for its light. And a radial texture gives us a softer edge. Glow is a separate effect that spreads bright pixels into surrounding image. Increasing the light won't automatically enable glow, though. The renderer and HDR 2 2D setting affect this setup. So, we'll show those settings before changing the value. Then, we'll test it with enemies and attack warnings on screen. The lighting needs to look good while we can still see what we're fighting. So, what we'll do is add an environment environment node. In world environment, I should say. I'll move it to the top, and then right below that, we're going to go ahead and add a canvas modulate. Go ahead and move this to the top as well. Inside of the color for this, I'm going to go ahead and create the take the HVS, and I'm going to go to 0.38. So, I'm going to go to the linear. Going to type in 0.73 or 37, sorry. We're going to type in 0.52 for the B, and then for the R, we're going to go 0.38. This will basically give us kind of a gray color. Um you can obviously adjust this as much as you want, uh but this is a pretty decent color for me. In the environment world environment, we're going to go ahead and create a new world environment. Open it up. Go to background. Inside of the clear color, we're going to select canvas. And then inside of the glow, we're going to turn that on. We're going to set the intensity to 0.45, strength to 0.9, and then bloom to 0.05. To be honest, most of these are pretty decent in terms of playing around with the number. The most dangerous, I would say, is the bloom. Now, obviously, play around with it, but the bloom is what makes things feel a little too intense sometimes. So, just be careful with the bloom, I would say. With the HDR threshold, we'll set that to 1.15. And everything else can stay the default. Okay. Now, inside of our brazier light, which we don't actually have, so let's go ahead and create that. Inside of our scripts, create a new script called brazier light. Inside of here, we're going to extend point light 2D. Because this is going to be a actual light that we create. We're going to add a couple variables here, flicker, base energy, and phase. Now, this is going to be the fun part is we're going to actually make this a real light, or at least imitate a real light. So, first, we'll set our phase to a random float with TAU, which is just a pi * 2, or 360°. Then, we will take our process function, and we'll take our phase plus equal delta. We'll say float or variable F is equal to the sign of phase times 6.1 times 0.6 and sign of phase of times 11.3. This basically advances the phase by time at two signs at different speeds weighted so that the slow one dominates and and then scale the energy up or down by flicker times that. 18% either side of the base. That's what the 18 is. Now inside of our dungeon script, we're going to add that. So the first thing we're going to do is create at the very top going to add our constant brazier light. We can actually add it here. I think that would make a bit more sense at the top bottom. Then we're going to create a texture for that light. So we're going to basically add the light in code because our braziers are being added in code, so we need to actually make them in code as well. Okay. Now at the bottom, we're going to add a new function for that. Static function radio light texture. This will return a texture, but the basic idea is I'm just going to fill in the texture to make an actual light. It's going to be 128 by 128. Um that's a It seems kind of big in retrospect of everything else, but because it's a light, it doesn't really have a shape per se. It's just going to look like a blob of something. So this is something you can definitely play around with, but for now this is pretty good. Now let's find the place brazier function. Here it is line 158 9 uh or you can just search control F, which is what I do. Now we want to actually create the light. So the way we'll do this is at the bottom, we'll create a new point light. We will set the light texture equal to the texture we just made. We're going to set the texture scale to 1.5. We're going to set our energy to 0.85. Uh it is pretty rare that I'll find myself putting the energy at one or above. Mainly because it tends to be too strong and then for the color we're going to set it at a kind of nice orange tone. And then the two last important parts is the script to add the script that we just created. So we'll say light.set_script to brazier light and then we'll add a child to the uh is this the sprite? Yeah. We'll add the child to the sprite or to the brazier basically. Now for this color right here, we can go ahead and replace that with a different one so so it has very different colors for the particles and for the light. Because otherwise before this would kind of blend in with the actual light and it just wouldn't really be that obvious and it wouldn't look super good. When the player walks behind the brazier, we want it to be drawn in front. When the player walks below it, that order should swap. Now Y sorting can use the nodes' vertical positions for exactly that. So we'll place the origins where each object meets the floor rather than assuring or assuming the middle of the image is in the right point. Different Z indices can affect the order as well. If an object keeps appearing in front, check its Z value, its origin, and whether it's part of the Y sort setup that we're using. Okay, another problem is inside of the combat room. We're going to go ahead and head over to the ordering and set Y sort enabled to true. I'm also going to go ahead and zoom out a little bit. I feel like the game is pretty zoomed in. So we're going to go ahead and zoom out to three. Once I've done that, the game is looking a lot different. And now we can see the braziers and the light. Now the game actually looks quite a bit nicer honestly in my opinion. You can see the the particles as well. They kind of distinguish themselves in color versus the light itself outside of it. >> Okay, now back inside the enemy base, we're going to find the function show telegraph. And right here, if the visible if the telegraph is not visible, we'll go ahead and play telegraph at a -4, which is basically getting our volume to -4. Next up, we'll find the show telegraph. Now, similarly, we need a if statement here to check for something. We'll check to see if the telegraph is not visible. We're going to go ahead and set our telegraph elapsed to zero. And then we'll also do the exact same thing we just added to the previous one, which is add the play telegraph at a -4 decibels. And then everything else is the same. Now, going to our room controller script, we're going to find the clear active room function. And right before or after the slow mo, we're going to go ahead and play the room cleared audio. Now, another small little fix here is inside of a lot of these scenes here, sometimes I load without the right now name when it's capital S or lowercase S. This path needs to match the file's capitalization as well. It might work here and then it might fail in another system or in the export. Okay, now it's your turn. Find one thing in your own project that's built but never connected. Something already written that never gets called. Give yourself about 10 minutes to do this. A quick way to is to search the project for a function's name and count the results. If the only result in the line is where it's defined, nothing is using it. You'll know that you've got one when you can point at the code and at the place where the call should be. Okay, here's one from our project. Juice has a squash function. We use it on the weapon, but the player never squashes. Not on our dash or anywhere else. And the enemy hurt sound is on our sound list, but nothing ever plays it. Neither one causes an error, it's just something that exists that we never touch. Searching for the name and counting the results is how we find them. We finish a fight and move on, but what did we get from winning it? So, now we can offer a reward that changes the next fight. Let's say we clear a room, walk into the next one, and keep going until the boss. If our character never changes, we can reach the boss with the same damage and same health that we started with. So, what's actually changing when as we go? So, after we clear a room, we offer three rewards and let the player pick one. That pick changes the character that we take into the next fight. We start with simple changes to our character stats, more damage, more health, faster movement, and a shorter attack cool down. Basic things. We can test the choice screen and see those changes in the next fight. Then we can add more items to do more that just change a number. All right, to start off, we're going to create a new script here called upgrade manager. This is where we'll manage and put all our upgrades. So, let's go ahead and open this up. We'll pop it out like this. And the very first thing is we will extend node, so that is good. But, we're going to go ahead and create a class name upgrade manager. From there, we're going to have a variable that will hold our rarity essentially. So, common, rare, and cursed. Now, cursed isn't better than rare per se, it's more so a different version of a rarity, which we'll get into as well. Let's say this card says it adds damage. Okay, but clicking some text doesn't increase damage by itself. We need the card's information and the effect that we're going to run when it's chosen. So, there's a lot to do here. We'll keep those together in an item dictionary. The ID is how our code recognizes the item. While the title is what we display. For the effect, we'll store a callable, which is a reference to a function that we can call later. We aren't applying every upgrade while creating the item list. We'll keep the function and call it when that item is selected. Then the same card interface can show different items without having all their effects written into the card itself. The first thing we'll do as well is add a ready function that will fill in this array. So we'll have sharpened, heavy soul, ball walk, swift boots, and rapid edge. You'll also see a number called corruption on every item. We won't use it in this lesson, but in the next lesson it becomes a cost. Taking a card raises our corruption, and the higher it gets, the more dangerous our fights become. For now, we just copy it with the rest. You take a moment to just pause and copy everything down, but the basic idea here is we're going to have a few different upgrade paths. One item adds eight damage. Another gives 20% less cool down. They both make us stronger, but are we doing the same calculation? No. Eight damage is a fixed addition. The cool down bonus multiplies whatever time we already have. 1 second * 0.8 gives us 0.8 seconds. Apply it again, and we get 0.64. That's also That also means that 20% less cool down isn't the same as 20% more attack attack per second. We'll describe the number the code changes. When we combine bonuses, we'll keep the order clear. Add the flat bonus damage to the base value, then apply outgoing damage multiplier. Now, obviously we have a couple of errors here, and we can fix this by creating the functions. Apply sharpened will have the player pass through where we'll take the player and we'll take its quick bonus damage and add eight. That's because right here we have eight. You can imagine the rest of these will be the exact same thing, just adding to whatever we need. So for the apply heavy soul, we'll say heavy bonus damage is plus equal 12. For the ball walk, we'll or bullwark, we'll raise the max health first then heal the same amount so the extra 25 isn't an empty bar. Now, this is also optional obviously if you depending on how you want the game play to go. In a lot of games when you increase the max health, they also heal that health that was increased as well. And then the last two functions we'll add is apply swift boots and apply rapid edge. For this small list, we'll keep each item's value in a dictionary. If we wanted to edit them in an inspector, custom resources would also be another option. Now, I'm going to go to head and close other tabs. And then I'm going to open up the player controller script. Because obviously we're adjusting things in the player's controller, but these things don't exist. So, first let's add our signal that we're going to have which we don't have actually any signals here. So, I guess this can just go on the top. We'll add signal stats changed. And I'll add a couple of variables here. I'm actually going to move around some of these variables because I realized my organization uh needs some skills. We'll have all the underscore ones together so I'll move all these here. And I'll move this here. Okay. Uh so, here are the ones that we're going to add. Quick bonus damage and basically just everything we just called that just doesn't exist yet. On top of that, we'll also have a variable items. This will hold all the items or upgrades that we take. This makes sense because as we play the game, we want the items and upgrades to be stored. At the bottom of our script, I'm going to go ahead and add a new function here has items. This will basically just check if we have that item using an ID with a string. So, we'll be checking things with names of whatever we're looking for. So, we'll for loop through the items and just check to see get ID if it's equal to ID, then return true. Otherwise, we'll return false. Pretty simple function. The next one is to apply the upgrade. We'll have an apply upgrade function where we'll take basically pass through the dictionary. We'll check to see the callable and then we'll call self and append the item into the items. And then we'll change the stats. Now, on this stats change, we'll have to actually call that. And that was basically just emit the signal stats changed. Now, for this, we'll have to go ahead and open up our weapon controller for this. So, we'll go ahead and open the weapon controller script. So, here we just need to adjust this function. So, we already have the profile. We'll get the base float and we'll basically just adjust everything. So, we'll already have the base, but we'll also add the bonus. That's basically it. So, we're just going to return the base plus the bonus now. So, the bonus will just add on top of the base. Now, for the CD mult, we'll have this to be adjusted as well. Instead of returning one, we'll now return the attack cool down multiplier. And that's basically the entire integration. Two functions that we wrote as stubs three chapters ago are now being applied to add the upgrades. So, it's a lot easier than it would have been if we hadn't written these. Now, inside the weapon controller, one thing we want to do here is find our player and we actually want to set this to player with controller node. And that's it. So, small fix, but we just want to make sure that it's uh setting the type as well. Now, for the move speed multiplier, we haven't adjusted or used that or done anything thing that. So, inside of the physics process, or the velocity, where we'll set that right here, we want to multiply by move speed, we want to multiply by the movement or the weapon {dot} move factor, but then right before that, what we'll do here is also multiply it by the movement speed multiplier. So, by default, it's one, so by default, it won't actually do anything, but once we adjust this with this will obviously be adjusted. And that's it. We could place each card reward by hand, but then we change the text or add another card, and now we have to move everything again. Containers can arrange those children for us. HBox puts them beside each other, and VBox stacks them vertically. Anchors position a control relative to its parent, while minimum size stops it shrinking below a chosen size. Can Once a container arranges the cards, manually dragging a card can get overridden. So, we'll change the container spacing and the cards size setting. We'll also let mouse input pass through the decorative overlays, so they don't just sit over a button and present prevent us from clicking. Now, I'm going to go ahead and close all the tabs to the right, and we're going to create a new scene here, where the base will be a panel controller. We'll have a VBox container under it as a child, and then under that, we'll have two labels. So, I'm going to go ahead and duplicate that one. And then we'll also have a button as a child of the VBox container. The very first node will be called the upgrade card. This one, we can just call it VBox, so it's a bit shorter. This label, we'll call it title. The next one, we'll call it DESC for description. And then this one will be choose. So, we only need one button, since we're basically asking the player, are we choosing this one this upgrade card or two other ones? So, in this case, I'm going to up call this upgrade card.scene. Go ahead and save it. For the upgrade card, we're going to go ahead and go to layout. And we're going to set the custom minimum size to 224 or 240 if you like. Something that you think is a good size, but I'm going to do 224. And then 268 for the the Y. Now, keep in mind, this is the cut the miss the custom minimum size. So, this will always kind of be the minimum size that this upgrade card has to be. Inside the description, we're going to go ahead and go to the auto wrap and we're going to select word. We're going to go to choose and we're going to type in take or choose actually might make more sense. We'll also take the description and the title. I'll select both of these. Set the vertical alignment to center. And the horizontal to center. For the description, I'm just going to put type in description for the text. And for the title, I'm going to type in upgrade. Now, we want to go ahead and create a new script here called upgrade card.gd. I'll go ahead and add this to my scripts. Create. And inside of this script, we're going to go ahead and simply extend can panel container but also have the class name upgrade card. We'll have two new things here, a signal and a variable. We'll have the dictionary that will store which what these are, what these upgrade cards are. And then we need to wire in the take button. So, we'll go ahead and say VBox.choose. We'll connect it to the choose pressed button. We'll also add a setup function which will basically just set everything up. This will do similarly to what we just did, um but obviously it'll set up everything up custom to whatever we want. So, if this upgrade card has a name or a title or description, it'll set that in. So, the title will be equal to the title of it. This will be equal to the description, etc. And then the rarity card will set the rarity color and everything as well. Now, obviously to fill this in, we'll create another function, rarity color. We'll have cursed, rare, and the default. So, default is basically anything that isn't these two. Now, lastly, we also will need the button that we just connected. So, on choose pressed, we'll disable the button, and then we will emit chosen with the dictionary that we just have. Now, don't worry about setting the dictionary, because we're going to do that later. Now, we're choosing rewards after a fight. The card needs words to display, but it also needs something to happen when we choose it. So, each item keeps its data and a callable for that effect. Keeping the callable doesn't run it yet. The selection does that. Then we need to describe the effect correctly. Adding damage gives a fixed bonus, while reducing the cool down by a percentage multiplies the current waiting time. Take that upgrade again, and it multiplies the new value. Containers handle arranging the cards as their text changes. Next, we'll connect this to room clear and check the whole choice. Open once, select once, apply the effect, then let the run continue. Now, for upgrade manager, we're going to create a new function here called get choices. This will literally just allow us to get the choices that we want. The first thing we want to do is just shuffle the pool. So, we'll duplicate our current array, and then shuffle it, and then slice it. Now, inside of our room controller, which we don't have here, we have to open that up. Next to the on ready variables, we'll go ahead and add our upgrades. But as you can imagine, this doesn't exist, so we need to go ahead and add that. So, we'll find our upgrades inside of our combat room. So, we do this by adding upgrade manager here, like so. So, now we have the upgrade node two as a child of the combat room, but we'll call this upgrades here. And now inside of our script where we got the upgrades, this makes a lot more sense. The last enemy dies. So, we open the reward screen once. But we can reach the code while Godot is still handling the hit. So, let's let that callback finish before we pause the world. We'll defer the reward call for that reason. We'll also mark the room busy, so another callback doesn't open a second reward. When a card is clicked, we'll hide the panel before applying it, so another click can't choose again. If we've waited before continuing, we'll check that the player is still alive. There are several ways to reach this code, so we need to check each one to finish before the reward choice and the correct pause state. Inside the room controller still, we'll also add another variable, reward is boss. And inside of our clear active room function, we're going to change a couple things. So, we're going to add a new function called finish room clear. Now, you can imagine this has a lot of similar things to what we have above, but this the idea here is that we're going to just actually have a slow motion effect as if we actually just cleared this room. This gives a cooler effect that we just cleared the room. Uh we're also going to have choices. This is where we actually get the choices, so three is the default. If it's empty, we'll upgrade the chosen. And then we'll show the upgrades in the HUD. Now, below this, >> We'll add another function called upgrade chosen. And of course, we'll apply the upgrades as long as the the upgrades definition upgrades are not empty. We'll set the paused to false. And if it was the boss, so the if the reward was the boss, we'll now enter the new floor. You can imagine this is kind of problematic to an extent because over here, that's where what we're doing here. So, we need to replace this function with a new one or different things. So, the way this function will work is we're going to call deferred the finish room clear at the very end. So, everything we just added will be called at the very end. But above that, we'd have a lot of similar things. So, we'll set the busy to true, active room is negative equal to one. So, it's setting it to false basically. We'll set the lower layer clear to equal or true equal to true. Then, we'll get the floor layer unlock room I. We'll set the room clear to plus equal one and we'll set the reward if the boss is equal to the boss. And then, that's it. Now, inside of the player controller inside of the physics process, we need to add a check here to see if get tree dot paused, then we'll just return. Picking a card should not start a new swing. So, if the tree is paused, then we want to just return before any of this other stuff happens. Now, inside of our HUD because we had called some HUD stuff, we need to add a new node here called we'll have it uh be a control node first. We'll add a control node and this will be called upgrade panel. Then, we'll go ahead and add another node. This will be an HBox container because we want to horizontally add our cards and it'll be called cards. Now, for the cards inside the layout here, we're going to have the separation. So, for the alignment, we're going to set this to center. And inside of the theme overrides and constant, we'll set the separation to 24. Now, going back to the upgrade panel, we'll get the layout and we'll do the uh anchor preset as full rectangle. And we want to hide this because this will basically just be hidden until we actually clear the room. Now, inside of the HUD a script, which I realized we never actually set, so there we go. We had it to the HUD. We'll open this up and then we will add or grab our upgrade cards that we just created. Now, we want to go ahead and add the on ready variables that we just created, so the upgrade panel and the cards. And at the very bottom, we're going to add a new function called show upgrades. Here, we'll basically for loop through the upgrades for the choices. So, we'll set through choices. We'll have on chosen, which will be a callable. We're going to first delete everything and then we'll add everything by instantiating and then adding child. We'll call the setup function, which we created previously, and then we'll just connect the chosen function that we want. So, this will connect the button to see if we're choosing or when we choose something. Once we do that, we also want to show the visible or show the upgrade panel, so set the visible to true, and we'll pause the tree. So, this is where we pause the tree and make sure our player can't do anything. Okay, we can pause the game to choose a reward. Cool. Except now what if we pause the reward screen, too? We still need to click those cards. Otherwise, I won't be able to either unpause the game, click a reward, and we're just stuck. The those process mode lets us decide which node gets to keep running while the game is paused. Gameplay nodes can inherit the normal pause behavior while a node set is while a node is set to always keep processing when the scene tree is paused. We'll use that for the parts of the interface and audio that need it. Our own code can still return early, though. So, always doesn't bypass every check that we write. Also, pausing the tree and changing time scale are very different controls. We'll need to account for both later when we actually end add the end screen. Now, what's important here is inside of our ready function, we want to go ahead and set our uh visibility upgrade panel to false just in case we don't do that inside of the scene here. So, if this isn't hidden, then that's fine. But then, we also want to set the process mode to always. This is very important because when we pause the scene, that is everything. That includes the HUD, but we don't want the HUD to be paused because I need to be able to choose which upgrade. We want common items to appear more often than rare ones. I think the reason is pretty obvious. But a normal random pick gives each entry the same chance. So, we'll give each item a weight. Add those weights and pick a number inside that total. You can picture each weight as a section on a line. A larger section has more chance of containing a random number. The weight belongs to that individual item. So, adding more items changes the total odds. Once we add choose a card, we'll remove it from this draw and calculate the remaining total again. That prevents duplicate cards in one offer. The unique flag separately controls whether we can offer one an item that the player already owns. Now, the very last thing we'll add is inside of our upgrade manager, we're going to add rarity. Now, the way this is going to work is we add a sort of weight, which we'll add as choosing because if we just have three different things and then choose randomly, it's not exactly equal rarity. We want to basically add a a weight to the rarity and say, "Hey, this is going to be like three meaning it's the most common, which makes sense. Rare is going to be 1.6 and then curse will be one. So, think of it as like one out of the total number of these." Now, at the very bottom, we'll add a new function where we'll weighted sample. So, we'll take the pool, the count, and we're going to duplicate the pool first. We'll create a new empty array with picks. So, this is the basically the array of three things that will return. We'll get the total weights of whatever's left. So, we have to for loop through it also. And then we'll we'll roll between zero and that total number number, then walk the pool adding weights until the roll lands inside of one. And then that's the pick. That's the thing that we take. So, we'll we'll for loop through that pool size and we'll append to the picks. And then we'll remove at I whatever pool that we have. We'll also add another function here at the bottom, owned unique IDs. This will basically make sure that we have unique IDs for everything so that we don't repeat random choices and have a bit more uniqueness essentially in our choices. Now, the last thing we need to do is replace the current get choices with a new function where we'll basically use the function we just made. So, the owned unique IDs, we'll just use that. And then we'll also use the weighted sample, which we also just created. So, we're This way we actually apply everything that we just created, but with more weighted samples. And if you test it out and kill the boss, you can now see that the weapons should pop up. So, we have sharpened edge, heavy soul, and rapid edge. And if I choose one, it takes me to the next floor. And I should have the upgrade, so that's pretty much it. There are two common items with weight three each and one rare item with weight one. On the first draw is the rare item's chance one in four or one in seven? It's one in seven. We add the weight of every item, so that's 3 + 3 + 1. Both common items count. When we remove an item after choosing it, we'll calculate the total again before drawing the next card. Even with simple stat rewards, we already make a choice when we pick one of the three. Choosing the damage card means leaving the other cards behind. For example, we might give up a card that raises our health limit and heals us or one that lets us attack again sooner. Which one we want can change as the run goes on. Now, that can work without adding a downside to every card. But if one reward is always the obvious good pick, adding more cards doesn't really solve that. We need to check why we keep choosing it. So, next we'll give some cards a cost to have some weight before we choose them. Okay, can you make an upgrade that you sometimes turn down even though it might help you? It could trade health for damage or change reach and attack timing. Give yourself about 10 minutes to plan out different things like this. Describe a situation that you'd want it and another where you'd prefer something else. Then test the effect inside the game. The trade here needs to matter in the actual game. Less movement speed might be a serious cost in one encounter and barely noticeable in another. You need to compare it with the other offers and the current build. If you can't find a reason to refuse it, adjust the trade or the alternatives instead of assuming a downside in the description guarantees a difficult choice. An upgrade should make us stronger. Okay, but what might make us turn it down? Let's add corruption as a cost to some of those choices. Okay, our game has a value called corruption. This is basically the downside or risk in our game. It goes up when we take card rewards and it can make the next fight more dangerous, increasing the enemies damage, making us more vulnerable, stuff like that. Every reward tells us how much corruption it adds. The corruption bar shows how much we've built already during the run. Every 25% of corruption moves us up a new tier, basically another danger level. The label next to the bar names that level. Stable, tainted, corrupted, or overloaded. Each time we move up a tier, our hits do more damage and enemy hits will hurt us more as well. Now enemies are also more likely to appear in a corrupted version, shown in violet, so we can recognize them in a fight. So before picking a card, we have to check how much corruption we have already, how much it adds, and we have to basically consider the risk to reward factor when choosing a card. So this damage card, for example, called the glass blade, gives us 25% more damage, but it also makes enemies hit hit 15% more. That's 15% more corruption that can push us into the next tier. Those are two separate costs and the screen needs to show both. If we only explain the card's downside, the player could take it and get a harder fight than they expected, basically making them feel like the game is unfair. So every card shows its corruption cost and the bar and the tier name needs to stay on the screen while we choose. When we reach a new tier, we announce it and make the violent enemies easy to recognize. And you don't need a corruption system to use this in your own game. Any cost works the same way, as long as the player can see it before they choose. For example, in Slay the Spire, trading max health tends to be a pretty common theme, or giving you curses. Um opening up our player controller, we now want to get started on implementing the whole corruption system. So, in here, we'll have two new variables. We'll add an export max max corruption and corruption. So, this is to keep track of our current corruption. We'll also add a signal at the top, corruption changed with a value and a maximum. Now, the important part is to add a function that tells us if we added corruption. So, here, we'll add corruption by just clamping corruption with the amount and the max corruption, of course, and then we'll emit the signal and then call stats changed. This is obviously important because we want to let people know, or other nodes know, that we changed the stats. Now, inside of our up apply upgrade function, we're going to change this just a little bit. We're going to delete this line on stats changed and we're going to add a new line, add corruption. Now, obviously, we can just delete that old one because this is called inside of this function. This upgrade makes us stronger, so why wouldn't we take it? Well, some upgrades should also add corruption, which can make later fights harder. We'll keep that value between 0 and 100 with different effects starting at different bands. Below 25 is the first band. Exactly 25 starts the second, 50 starts the third, and 75 starts the highest. We need the label and gameplay tracks to use those same boundaries. Otherwise, the HUD might show one tier while enemies spawning or damage uses another. We'll test the values on both sides of each boundary so that we can see that they change together. We'll also add another function get corruption tier. This will basically just return different strings depending on what kind of corruption we are at at the moment. Now, this is a pretty good leveling system to an extent because 25 each apart is pretty decent. If you want to do 1/3 or even more than that, then that's totally fine as well, but four is a pretty good number. Now, on the top we'll add new variables. Glass damage multiplier and glass taken multiplier. Or mult in this case. Now, I'm going to our upgrade manager. At the top we're going to add a new dictionary. This will literally just be glass blade. And so we're going to make a new dictionary that will have a new item essentially. So here it'll be a cursed rarity. So obviously you can see that previously I didn't have any cursed items. So we need to add one. So for this one we'll simply add a function. Uh probably right here actually. Apply glass. So we'll apply the multiplier by multiplying it by 1.25 and by getting the player. And that's it. Now, inside back inside of our player controller near the bottom we'll go ahead and add a new function corruption damage multiplier. This will literally just return our numbers depending on what kind of corruption we're at at the moment. We'll return one by default. But if we're greater than 75, meaning we're close to 100, then it'll be a pretty big number, 1.22. All the way back down to one. We'll also add a function corruption taken multiplier. This will allow us to do the same thing just damage taken. We also want to create a function that allows us to return the number for outgoing damage. So of course we need to get the corruption damage multiplier and then multiply that by the glass damage multiplier. Now, inside of our weapon controller, we want to find the compute damage function. And inside of here, we'll simply add on to the return. We'll just simply say return the base plus the the bonus, and then also multiply it by the get outgoing damage. This will allow us to multiply the compute damage every time by just adding whatever multiplier is here. Now, again, going back to the mult the player controller, we want to go ahead and find our stats changed function. And right here, the before we emit, we're going to go ahead and say hurtbox.damageMultiplier is equal to the corruption damage corruption taken multiplier times the glass taken multiplier. We'll go ahead and close this. And inside of our HUD, we're going to go ahead and add a new health bar or a bar. So, I'm going to actually duplicate this and just rename this to corruption bar. I'm going to move this probably, honestly, to the top right. May could make sense. But for the color, we can go ahead and change this to a more I don't know, something purple would probably make sense. Uh the ghost color maybe something a bit lighter. So, if you want to copy these values, go for it. We'll also add a new label. So, I'm going to duplicate the status label and then rename this to cure label. I'm going to go ahead and drop this below the corruption bar. So, kind of right there. There we go. Now, inside of our HUD, we need to go ahead and load those functions or load those nodes that we just added. So, the corruption bar is a stat bar. So, honestly, it would maybe make sense if I add that right below the other stat bars. Inside of the process function, we're going to go ahead and add a ratio for the corruption bar. So, we're going to say corruption bar.setRatio uh with the player's max corruption and the current corruption. And then for the label, you might be wondering, "Oh, what is that for?" Well, that is for the corruption tier. So, in this function, if you recall, that is exactly where we have stable, tainted, corrupted, and overloaded. So, that is where we'll print or show that text. Now, inside of the upgrade card, inside of the setup, for the description specifically, this is where we want to add right here, we'll add corruption is equal to the corruption basically. And we'll do this by getting a new line. So, this means new line. This is going to get the value of is whatever is there to the percent. So, this is the string, and this will get the value of whatever we want here. So, in this case, it would be the corruption. Now, at this point, you can go ahead and test the game. So, if you want, pause the video and test it out. See you what if it works and see if the corruption works. Taking the reward cards raise a value called corruption. Every 25 points move us into a new tier, another danger level, increasing both our damage and the damage that enemy hits do to us. You might ask whether those changes cancel out. If both went up by the same amount, would we be right back where we started? Not necessarily. Hitting harder might kill one enemy a hit sooner. And not change anything else. In another case, if one enemy's hits hurt more, we might survive one fewer hits. Those two changes don't have to line up. So, we need to check both against the enemies that we're fighting. Now, in our game, the two increases aren't even. At the highest corruption tier, the tier bonus makes our hits do 22% more damage, while enemy hits do 40% more. The incoming damage increase grows more than the bonus to our own head. This way it kind of balances the risk and reward again. Now, that's why the percentages alone can't tell us whether the trade is fair. We play the same fight at a few corruption levels just below and just above tier change and count how many hits each enemy needs and how many we can take. That comparison is what we use to adjust the numbers. All right, now let's open up the juice script and we're going to add a new script here or a new function. So, this function is going to act very similarly to our old function that damage numbers, so this one where we just pop up text. So, let me show you with the new script with the new function. It seems like quite a bit, but it's a very simple uh function in comparison. It basically does the exact same thing, but this time it's simply floating text rather than a number. So, almost everything is exact same, but you can see that we're just going to be floating the text. We gain one corruption and update the bar. That's fine, but but do we also want the bigger tier message every time that the number changes? Well, only if we've actually entered a different tier. So, we'll compare it with the tier that we last displayed. If they've if they're the same, then we return. If they've changed, we store the new tier and show the message. We'll do a similar check when corrupting an enemy. Applying its stat multiplier again would make it stronger a second time. So, we'll remember that it's already corrupted. A function might get called more than once even when we only want its effect once. Now, for the player controller, let's go ahead and pop to the top and add a new variable here. last tier And then inside of our add corruption function, I'm going to go ahead and write above the status changed, we're going to get the tier and we're going to again get it with the variable. And basically check to see if the tier got changed. If it did change, then we'll call the function on tier change. Now, for this function, this is where we'll actually pop up the text and show people that, "Hey, we changed the corruption." So, in this case, we can add this to the bottom. We'll basically shake the camera. We'll play telegraph at a lower pitch. We'll get our world scene and we'll play in the global position of the player controller just above him and just say that we are now in a new corruption by saying the tier to upper. So, this will take all the letters to an uppercase. Once we've done that, we can go ahead and open up the enemy base script. Pop up to the top. And we're going to add a new function right above the knock up or knock back. We're going to say is corrupted is equal to false. We'll add a new function at the very bottom here called make corrupted. This will act very similarly to making the player corrupted, but in this case, it's making the monster just stronger overall, increasing the max health, increasing its damage and speed, its damage, which I already said, attack area. And then of course, we'll set its outline and modulate its color as well a little bit. To actually apply this, we'll go ahead and open up our room controller. And inside of our spawn function, we're going to go ahead and add right between the add child and the spawn in. Anywhere in between, so we can just add it right here if I'd like. We're basically going to say make corrupt. And if E has method spawn in, then we'll spawn in. Which I realize is a repeat. And then so we'll call that make corrupt, but we need that function, so we don't have it. So inside of the room controller script still at the very bottom, we'll add a new function make corrupt. So here we're going to basically just say if the enemy has make corrupt, then we'll just return. Or if they don't, sorry, then it will return. And then if they do, so if they do, we'll do all this. So we'll just call the make corrupt, but we'll also have the chance to see if they are actually corrupt. So these are all just percentages. So 60% almost 40% and almost 20%. What if we don't want any of the rewards? We'll add a skip option, but skipping still needs to close the panel and continue the run. We'll use an empty dictionary to mean no item was chosen. The receiver checks for that before applying an item. Cleansing is different. We did choose an item and it reduces corruption through the shared corruption code. Its other effect though can do nothing. So we need both cases to finish the choice properly without treating a cleanse as though we skipped it. Now let's head back to our upgrade manager and we're going to go ahead and add a new item again. This one will be a cleansing light, so it's pretty much the opposite of corruption. So you can imagine here we're doing minus 25 corruption. It is literally a cleansing light removing some corruption. Now this one doesn't give it a crazy effect or anything. It literally just purges corruption from our weapon. And that's kind of important because we need a way to remove debuffs because corruption is in essence a debuff. At the top we'll also add a new constant uh cleanse minimum corruption. Now inside of the get choices, we're going to go ahead and pop this in right instead of replacing this. We're basically going to add two lines. Basically checking to see if the corruption is a less than the minimum corruption and then we'll continue and then we'll again append. Now obviously we still have a couple things apply noop doesn't exist and the corruption doesn't exist so for the apply noop what we'll do is we're simply going to add a function apply noop but we're not actually going to do anything. Cuz this doesn't do anything so we're just going to add it to get rid of the error. So we'll just pass. For the player corruption we can add that right below that as well. Here we'll simply return the player corruption if P is not equal to null meaning if it exists then we'll actually just return it. Otherwise we'll also return zero. So right here this will be the skip a button. Here we can say take nothing cuz this will basically just say hey if you don't want any of the options of the upgrade cards then you can take none of them. So it wouldn't make as much sense if we added take nothing and inside of each card because if we have three cards and we don't want any of them we want one button that just says take nothing. So now inside of our HUD here at the top we can go ahead and add a upgrade callback callable. And then we'll add a new function called skip upgrade. We'll add this at the Actually add it at the top here. Skip upgrade and it's literally just going to do exactly what we said skip the upgrade. It'll call the callback with the empty dictionary. We'll set the upgrade panel to false and we'll just make sure that it's not a if it's not visible we'll just return. Now inside of the ready function we want to go ahead and say upgrade panel slash skip pressed we'll connect the skip upgrade button. And then going down in the show upgrades right before the for loop here we want to go ahead and say upgrade callback is equal to the on chosen. And that's it. Now you can go ahead and test it and see that we can now skip buttons or we can skip cards. In a test, set corruption to 24, then 25. Which one starts the second band? Then try cleansing when we have a small amount left. What should stop it going below zero? 25 it starts the second band. The clamp inner corruption update keeps the value between zero and 100, including after cleansing. Check the label and gameplay condition at the exact same value. So they agree about which band we're in. We clear room and get one choice, but two callbacks or quick clicks could reach that code. So we've added checks to avoid giving that reward twice. Each item has a weight in the draw. Once we choose and remove one, the next draw has a different total. Now corruption makes some rewards cost more than just the choice of another card. Exactly 25 it starts the second band and the HUD and the gameplay need to agree about that. But what if we skip? We pass no item and still finish the choice. Cleansing is different. We choose an item whose corruption change still needs applying. Try both before moving on and make sure that either route gets us back to into the run. Okay, add two upgrades with corruption cost and compare them with the existing item table. Give yourself about 15 minutes to do this and compare each one with an existing reward that does something similar. Why would you choose yours rather than the other ones? When would you choose the other ones? Because everything we need in the game still needs to be somewhat usable. There isn't one conversion rate that makes health, damage, cool down, and special effects equivalent. So, compare similar items first, then play the same encounter with each option. If yours is always preferable, adjust its effect a little bit, its cost, and availability. If it's useful only in one particular build, check that the player can recognize that situation from the description. Now we have a cost to think about. Next, what if two items do something different when we both own them? Or when we own both. Let's build those combinations. Okay, so far our cards mostly change a number. We could keep adding bonuses like that, but what if a card changes what a hit does? An upgrade can add an effect to our hits, giving us another reason to choose that card. One upgrade called Ember Brand makes an enemy burn after we hit it. Another could call be called Frostbite, slowing the enemy down. And Storm Coil sends damage from one enemy to another enemy that we hit. Basically, a chain reaction essentially. So, think about the fight we're having here now. If we need to hit once and then back away, burn can keep hurting the enemy while we're out of reach. So, it's pretty useful. If we're struggling to get away from an attack, slowing the enemy can give us more time. If enemies keep gathering together, then Storm Coil's damage jump can help us hit more than one at a time. The description tells us what the upgrade does. We also need a fight where we can see why we'd want it, though. Okay, imagine we pick up a burn item that changes an effect value on the player, and the hit code uses it when we attack. Now, we also own a chain item. So, the question is, does the chain automatically spread the burn? We need to check for the pair and write that combination ourselves. A synergy flag tells us the hit code that we own both. Then, the code can apply the burn through the chain. The items give us the values, and we still decide what those values make happen. Okay, there's one more item in this group called Reaper's Mark. When our hit leaves an enemy at 14% of its health or less, Reaper's Mark will finish it off straight away. Basically, it's called an execute. So, the player gets four effect numbers, and they all start at zero. Burn damage per second for Ember Brand, how much Frostbite slows an enemy, how many times Stormcoil's damage can jump, and the execute threshold for Reaper's Mark. Each item adds to one of these numbers, and the weapon reads them when the hit lands. All right, inside of our player controller, we want to add a couple new nodes. We'll add them at the top near the corruption. We'll basically add a burn DPS, which will be for Ember, chill factor, which will be for Frostbite, a new item, chain count, which will be for Stormcoil, and execute threshold, which will be for Reaper's Mark. These are all basically new items and things that will help us actually use them. Next, we'll add four flags. Each one is true when we own a particular pair of items. Plasma is the pair that we just looked at, Ember Brand and Stormcoil. The other three use two items, so we'll build later in this lesson. Echo Blade, which makes every swing throw a slash across the room, and Mail Storm, which turns our heavy attack into a spin that hits all around us. Glacial is Echo Blade with Frostbite, so the waves chill harder. Now, Cyclone is Echo Blade with Mail Storm, so that the spin throws sound waves outwards. And Harvest is going to be Reaper's Mark and Ember Blade, which raises the execute threshold. Now, they all start as false by default and each one gets read in place where its effect happens. Below that, we'll add four more. We'll have sin plasma, uh glacial sign sin clone, cyclone, I don't know my uh harvest and yeah, that's it. Now, we'll also add some a dictionary here. So, we'll add synergy description, plasma which will be chain bolts also ignite with the arc two and you can kind of read the rest. From there, we'll now have a new function. We'll add the new function at the very bottom. This will be called resolve synergies. We'll basically see if we have the item that is uh with the has item storm coil. So, if ember and storm coil, then we'll see if there's synergy basically. Now, inside of our up apply upgrade function, we want to add something here which will literally just be right before add corruption, we'll resolve the synergies. Now, inside of our upgrade manager, we need to go ahead and add those new items that we just applied since it doesn't actually exist yet here. We'll go ahead and add these new dictionaries with amber uh browned, frostbite, storm coil, and reaper's mark. Similarly, we'll need a function for all four of these though. So, right below that, um we can maybe add it at the bottom, that might make most sense. Now, what happens if we collect several copies of the same special upgrade? Now, frostbite is the card that makes our hits slow enemies. Now, there's obviously two obvious options here. Either we make it so frostbite never shows up again or we can just make it so each copy adds 30% more slow. Now, take three with no limit. That adds up to 90%. At least with linear scaling. So, the enemy can barely move now. But in our version, it'll stop the slow at 85%. So, enemies can still kind of walk towards you, but the effects actually stack well. Now, a storm coil is the card that sends and damage to nearby enemies. When we hit an enemy, that damage jumps to the nearby enemy as well. And nearby extra copies of that card adds another jump. If the chain doesn't remember who it already hit, it can jump straight back to the first enemy that we hit initially. And then just keep bouncing between the first like two different enemies. So, the chain needs to keep a list of the enemies that it already hit and skip them. Now, it never makes more than eight jumps, no matter how many storm coils that we take. We can test both limits with the normal item values, then with much higher ones in a test copy to check whether that limit holds. Then we play a normal fight against the enemy slowed to it to the cap. We still want its attacks to be a threat and the fight to be easy to follow. If slowing enemies makes every fight easy, then we'd have little reason to choose another card. Right below player corruption, we'll go ahead and apply and create apply ember, frost, storm, and reaper. Each one will basically do something. So, this one will apply burn by adding. This one will clamp the float. This one will get the minimum integer and this one will get the minimum float. Heading back inside of our player controller, we want to go ahead and add a new function. Again, we're going to get get execute threshold. This will basically return the clamp float of our execute threshold times 1.6 if this is true. Otherwise, we'll have it get multiplied by one with a zero and 0.75. So far, every hit reaches an enemy through its heart box when our sword's hit box overlaps it. But when storm coil's damage jumps to another enemy, nothing touches that enemy. The damage just decides that it gets hit. The same goes for an extra hit from a from an item that we'll add later. So, we'll give an enemy a second way in. A take damage function. It lowers the enemy's health, flashes the sprite, and shows the number, and knocks it back. The same as a sword hit. But, if the enemy is already dead, it'll just do nothing. Now, I'm going back to our enemy base. We're going to find the take damage function, which doesn't exist. So, we're going to have to create that. So, inside of here, at the bottom, we'll create a new function, take damage. And inside of here, what we'll do is we'll first of all return true, or just return, sorry, if we are dead. The state of the player, or monster, sorry, is dead, then we'll just return. Then, we'll say health.damage with the amount. We're going to flash and damage number. We apply the actual numbers, and then we will apply knockback. Our burn says 12 damage per second. So, do we apply 12 every update? Well, now we're doing 12 damage many times in a second. We need to choose how often burn ticks, and multiply the rate by that amount of time. At a quarter second interval, 12 per second becomes three times, three damage per tick. We also need a timer for how long the burn lasts. Refreshing that duration doesn't necessarily increase the damage rate. Those are separate choices we'll make in the function. For The simple timer also won't perfectly catch up after a long frame stall. So, we'll test how much damage happens after actual elapsed time. Now, similarly, we will also want to apply the status effects that we just created. So, we'll add a few variables, burn DPS time tick, chill factor, and chill time. And then, at the very bottom, we can go ahead and add a couple functions that use these. So, first we'll add ignite, which basically just ignites the monster. We'll have chill, which does pretty much the same thing, but in this aspect, uh we're going to clamp at the float first on the chill factor. And then we also do need to apply these because none of these actually do anything yet. They just change the values over time. So, to apply this, we'll have tick status. So, here we'll say if burn time is greater than zero, we'll apply the burn. Here for the chill time, we'll apply the chill. Now, at the very top, we'll find where we have the AI process. And right after that, we can add tick status. Now, after the ticks, we should actually check to see if we are dead. And if we are, then we'll just return. Okay, let's say the enemy wants to move at 100 and chill half its speed. We should get 50 each update. But, if we keep that reduced value and half it again next time, we have 25. That's 12 12 and 1/2. That's why we'll keep the AI's intended velocity separate. The AI updates that value, then we apply chill once when calculating the final movement and add the other effects. When chill ends, we can use the intended velocity without trying to reconstruct it from a value that we've repeatedly reduced. And then hit stun will stay, the player factor will stay. Now, right before the velocity, we're going to also add another check here right before the velocity, and this is actually very important that it's before, is if our chill factor is greater than zero, then we need to adjust the velocity. We need to take our velocity and adjust it by saying times equal 1 minus the chill factor. And the knockback will stay unchilled, which kind of makes sense because the knockback is usually my weapon knocking it back. And if it's knockback is affected by the chill I also apply is kind of anti-synergy. So, we'll keep the knockback on its own. All right, inside of the enemy base script, another fix we're going to do here is inside of the physics process function. At the very top, we're going to set a variable that just gives us the AI velocity. And then right above the AI process, we're going to set the velocity to AI velocity. And then right after the AI process, we're going to set AI velocity to velocity. Okay, let's say an enemy has 30 health and our hit brings it down to 10. Now, an execute might finish it, but what if we checked for execute before applying the hit? We'd still be looking at 30 health and could miss it. So, for this hit, we'll update the contact, apply damage, then run the follow-up effects. We'll skip anything that's already dead. We also need to pass the supported effects into our slash wave projectile when we add it. Okay, now inside of our hit box component, we need to open that up. And this looking pretty empty, so let's go ahead and fill out some things. The first thing we'll do is we're going to get rid of the hit land emitted. And we're going to add a new function that is called by the hurt box once it's damaged, which will be notify hit. And we'll just move the function here basically, or the emit, sorry. Now, closing this and opening up the hurt box component, that is where we'll actually call those things that we just added. So, we should already have this one, so if we have we have the has method on hurt box. Right above this, we're going to add a new function or new check, basically the exact same thing, so we'll check to see if we have the notify hit. Uh if we do, then we'll call it. We'll call it on self. Now, at the top of this, we want to go ahead and add some more safety checks. So, we have three already, but we're going to add two more. The first one is going to be if area is um queued for deletion, we'll return. The next one will be if the health is null or if health is uh is a is not alive. So, if not is alive, meaning it's not, then we'll return as well. So, these are some additional safety checks, basically. Now, inside of our weapon controller, we want to go all the way to the bottom and add a new function called apply hit effect. This will apply all the effects that we actually want. So, first we need to access the enemy by saying get uh hurt box. And if the enemy is null or is not instance valid, then we'll just return. After that, we'll simply apply the two burns or the burn and the chill by saying if um player.dps is greater than zero, if the chill factor is greater than zero, and the enemy has these two methods, ignite and chill, then we'll apply them. Now, once we've done that, we want to go ahead and see if the player's execute threshold is greater than zero, and the enemy is an enemy base, then we'll basically just see if the execute threshold is valid, then if so, we'll just kill the enemy. Now, the last thing we want to do is inside of the on hit landed function, is at the very bottom, we're going to go ahead and apply the hit effects with the underscore hurt box. Here we go. The chain hits one enemy and jumps to the nearest one. Cool. But, from that second enemy, which target might be closest? The one that we just came from or it's the one that we just came from. So, we'll remove every target that we've already visited, including the starting enemy, before looking for the next hop. each hop uses one of the allowed chain steps. In this version, each hop deals half the computed attack damage. We aren't having the previous hop again. We'll also reject dead enemies, even if their nodes still exist while fading out. That gives us a limited chain through different living targets. Next up, inside of our weapon controller, we want to go ahead and add a new function that will be chain to nearby. Every enemy this bolt touches, the origin is in there before the loop actually begins. So, that's going to be the whole complication here. So, we'll have a dictionary with origin is equal to true from, which is the node, the original node basically. And then, we want to count the hops. So, to do this, we'll start with a for loop. And then, we'll have another nested for loop where we'll loop through, first of all, we'll loop through the count that we actually passed through. How many chains basically, and then we'll loop through the enemies. We only want to continue if everything is valid, because if nothing is valid, we'll get an error. And then, once we actually do, we'll get the distance between each one. We'll look for basically the best distance, like the closest one essentially. So, if something is less than this, then that's good. Now, from there, outside of this for loop, outside of the inside for loop or the nested for loop, we want to go ahead and check to see if best is null, then we'll just return. This means we couldn't find anything to chain. If we do have something, then we'll find the best the monster, the next monster to take damage. Well, it'll take damage, but it'll only take half. Now, the cool part about this is because it's in a for loop, this will basically happen continuously until it chains is done. Or until the count is done. One more fix is inside of our weapon controller at the chain to nearby function. Right below the if statement here where we have this check, we want to do one more safety check where we'll basically check to see if the enemy is dead or not. And obviously we don't want to chain to something that is dead. So, we're going to check for all that and continue if it isn't. Everything else will stay the same. We just want one more safety check. Now, to actually apply this inside of the apply it effect function at the very end, we're going to go ahead and check to see if the player count is bigger than zero. If it is, we'll chain to nearby with the enemy and the chain count. A chain starts A and hits B. When it searches again, A is still the nearest enemy. What needs to be in the visited list before the first hop? Well, A. A needs to be there already. Otherwise, we can just chain straight back to it. Then we'll add each new target as we choose it. Reject dead ones and reduce the number of hop count. That keeps the chain moving through different living targets and gives it a stopping point. And once we've done that, we want to go ahead and head back into our upgrade manager. I'm going to go ahead and save so our weapon controller saves and we'll add in a few more items. Okay, these three change what our attack does. Instead of adding to a number, Echo Blade makes every swing throw a slash wave that flies forward and keeps going through enemies. So, the sword can hit from across the room. Mail storm, which the code calls whirlwind, turns the heavy attack into a spin that hits all around us. And twin fang curse, called twin strike in the code, adds a second hit for half damage. All three are unique. Owning mail storm twice would do nothing extra. So, once we have it, the draw stops offering it. We're going to add a Echo Blade, Whirl Blade, and Twin Strike. Now, for each of these, we want to go ahead and add a function for all of them. So, at the bottom of all these functions, right here, I'll go ahead and apply apply echo, apply whirlwind, and apply twin. So, for echo, it'll be a integer, and the other two will be booleans. So, we do need to add these ones as well. So, let's go ahead and head over to the player controller. And at the very top, we'll go ahead and add those things. We'll add echo level, whirlwind, and twin strike. Now, heading back to our weapon controller, again, inside of the apply on hit effect, similarly, we'll basically check to see if a player and twin strike and enemy is enemy base, and if the enemy health is alive, then we will say enemy take damage, compute the damage with the player's global position. And that's it. Now, we do also want to add the whirlwind effect. So, let's go to the top, add that as a variable here. And then inside of the begin active function, right here, right after the size, or after the size is computed, we will add is whirlwind, and it'll be computed basically here. Then, we'll check to see if whirlwind. If whirlwind, then all we want to do here is check to see or not check, sorry. We will set the variable D with size and then offset. So, this will adjust our size and offset depending on if whirlwind is true. We increase the whirlwind size, but the hit box is still small. How come? If we already gave the collision resource the old size, changing a separate variable afterward go back and update it. So, we'll choose the final size and offset first. Include the world wind override. Then we'll assign them to hit box. We'll follow the same order when spawning a slash wave. The set the values its ready function needs before adding it to the tree. Otherwise Otherwise, ready can run using the defaults instead of the values we intended. Then inside of the weapon controller, we're going to go ahead and replace the size offset and the is world uh is world portion in this uh begin active. So, right here on this line, we want to go ahead and move this up above all this. So, we'll basically copy paste all the way from here, go to this line, enter enter, and then copy paste again, and that's it. Everything else stays the same. So, we don't need to write anything new, we just need to change the code a little bit. Now, for the slash wave, the other item that we have, we need to create a new script. So, let's go ahead and create a new script here. This will pop into our scripts folders. This will be called a slash wave. And we'll go ahead and create. Now, this will by default be an area 2D, or it'll extend area 2D, I'll say. The variables we'll need are going to be speed, damage, knockback force, lifetime, and source node. We'll also extend burn DPS, chill factor, direction, life, and hit. We also want to configure this node, so we'll have a configure function with direction being set, damage, uh source node, and rotation. Once we've done that, we want to go ahead and add our ready function. So, we'll add it to group hit box. We'll connect the functions that we need. And we'll also create a tween for this. Once we've done that, we want to go ahead and add our physics process. The basic idea here is it's just going to move itself, and then also count down. So, it'll just basically count down with the life, and then once the life life is bigger than lifetime, it'll just die. So, it'll queue free itself. Now, before we end this script, all we want to do here is add a function try register hit. It'll pass through a hurt box, and we'll basically check to see if it has hurt box. Then, we'll return false. If it doesn't return false, that means we can continue basically and append hurt box. Then, we'll get the enemy by getting the hurt box.get_parent, and then we'll say if is valid basically, if it exists, then we will ignite and chill if we have those two things. Otherwise, we'll just return true. This is basically to just register a hit. Now, to actually make this scene, let's go ahead and pop a new scene here. We'll create an area 2D as the base. We'll add a collision shape. We'll rename the area 2D to slash wave. We'll go ahead and add a capsule here. And I'm going to rotate it 90°. Once I've done that, ideally we add a crescent shape or some sort of slash wave. If you want to look into making a shader for this, again, I have some on my website that will take you through a guide. But, in this case, because we're not going to go through that, we'll go ahead and just add something that looks like a missile or some sort of shape. So, let's go ahead and add this here to the center. I'm going to reset its position to 0 0 and set its rotation to 90. We'll save this as slash wave inside of our scenes folder. We'll go to the slash wave node here, and we want to go ahead and set the collision to six for the layer, uncheck one, uncheck mask for one. No, sorry. We are going to check one for mask and that's it. So, one and six here. One catch with the mask one. Our walls are on layer one, but so are the enemies' bodies. So, when a wave reaches an enemy, it also touches the enemy's body and freeze itself. And the hurt box skips any hit box that's about to be deleted. The wave would still burn and chill, but most of the time it wouldn't deal its damage. So, in the wave scripts, we'll only free it when the body it touches isn't an enemy. Now, the wave cuts through every enemy in its path and still stops it at a wall. Now, similarly, because we did add it in code, uh what we can do here is add this, first of all, the script, but we can also add this scene here to hit box. So, we did do this in code, but you can also do it in the scene if you want that visual. Uh it doesn't do anything if you have it in both. Uh I think once it add tries to add it to to the in code, it'll just see it's already added and it it won't do anything. Okay, now from there, we want to go ahead and load that uh slash wave that we just created. So, at the top, we'll go ahead and add a constant slash wave. And then inside of our begin active function, near the bottom, we'll go ahead and check to see if the echo level is bigger than zero. I don't And then, if it is, we'll throw the wave. Once I've done that, we actually need to add the throw wave function. So, at the bottom of our script here, we'll go ahead and add that. So, this function seems like quite a bit, but it's pretty simple. We basically have one wave per echo level. We basically fan along the swing cyclone turns into a whirlwind with heavy into a full ring instead. So, first of all, we need to get the count with the echo level, the as ring uh boolean, which will be as world and if cyclone sync cyclone. We'll check to see if as a ring, if it is, then count will be the max int of count times four and eight. Then we'll for loop through the count. And we'll basically instantiate and create that wave. We'll configure it burn DPS. We'll basically set everything that we just added inside of the slash wave. Once we've done that, we want to just add it to our container. We get our container projectiles and then we add it and that's it. Now inside of the animate swing function, we do still need to add a couple functions. So here, or not functions, we'll we're going to call basically a couple tweens. We want to add the rotation of the animate swing for the is swirl. First, we'll create the uh tween that we want here. So the weapon tween. And then all we can do here, or need to do, is tween the property. We'll tween its rotation. And then once that's done, we'll simply tween its weapon sprite rotation again and then return. That's it. Okay, we've handled the whirlwind. So return ends this function call. Otherwise, we continue into the normal swing animation below it. Now to actually make this work, one note we need to make sure is we actually have the projectiles here. So it's been a while since we've used this, uh but yeah. Make sure that we have any projectiles node uh because otherwise the projectile we add won't go anywhere. We've added several effects and the out order starts to matter here. We pick up an item, then check whether we now have both parts of the synergy for it. Burn uses its damage per second and take interval, whereas chill uses the intended velocity, so we don't keep having a value we already have slowed it. The chain, remember, is is target, so it can't just jump straight back to its enemy that it just came from. And the whirlwind chooses its final size before giving the size to the head box. If something looks wrong, pick one effect and follow the value through those steps. Testing everything together first makes it much harder to see which calculation goes wrong. Once each one works, try the combinations. We want to open the codex and see what we've picked up. But the number of items keep changing, so we can't just write one fixed label. We'll keep a line for each owned item and collect those strings in a packed string array. Join com Join combines them into one string with a separator between each entry. We'll use a new line, so each item gets its own line. A normal label can show that text, too. Rich text label gives us formatting options such as BB code. We'll rebuild the text when we open the panel, so recent items appear and make sure opening and closing it also updates the game pause state. Okay, now at this point, we want to go ahead and add a codex. If you recall in our project settings inside of our input map, we had a while ago we added this codex tab, which we haven't really touched at all. Now, where this will go is in our HUD. Make this, we're going to go ahead and create a control. We'll rename this to codex panel. We're going to add a rich text label. We'll go ahead and also add a button. This button will be called a close. The rich text label will be called build text. And now for the button, we do want to go ahead and just fill the text close, and that's it. For the codex panel, we want to make this a full rectangle. But we're going to go ahead and hide it by default. For the Although for the build text, I'm going to move this to the center a little bit and just make it a little bigger. And now that's it. I'm going to go ahead and close the codex panel and head over to our HUD script. Inside of here, we're going to go ahead and add a refresh codex. It'll be a function that will literally refresh the codex. So, here what it'll do, it'll basically access our player by getting the game manager player. We'll basically look for the owned items, so the items that it has and just fill in the codex. So, we'll get the ID by getting the synergy descriptions and we'll append the lines inside of the codex. To open the codex with tab, we use a function called unhandled input. Godot calls it with every key press or click that interface didn't already use. So, pressing tab won't fight with a button that we're already clicking. Now, we check that it's our codex action, ignore the repeats that we're getting from holding the key down, and leave it alone while the reward cards are showing. Opening the codex pauses the game and closing it will just unpause. Now, at the top, we're going to add a unhandled input event function. So, here we'll basically get the codex and show it if it's visible or not. Uh in this case, we can actually just put this on the same line. And in this case, we do need to delete the semi colon or the colon here. And we'll also have a function at the bottom, just close codex, that will allow us to actually close the codex or not. And then inside of the ready function, we do need to just make sure we add somewhere, probably at the bottom, that we make the codex uh visible equal to false and we connect the close codex uh button. Once we've done that, we can go ahead and head over here and actually just move our buttons and text where we want. Now, so this seems pretty decent. I think for the button, I'll move it down just a little bit. And there we go. Now, one note is for the cards, we can actually just move this to the center. This will also just make more sense. Just so it's a little nicer. And then for the skip, we can go ahead and add that only to the bottom as well and make that a little bigger. Hopefully, you've kind of played around with the positions and I everything for making these look a little better because we haven't really spent much time on that. But, aside from that, that is pretty much it for this part. We are complete and done and now you can go ahead and test the codex if you'd like and everything we just added. Add one more effect value and an item that changes it. Give yourself about 15 minutes for a small version here. What happens if we take it twice? How far should it stack? Pick a limit, then try it with one effect that we already have. Keep the test to one or two enemies at first though. You could try healing a little when a hit counts or changing the knockback, but when does that effect run? Can hitting a dead target still heal us? What happens if we hit several things too quickly? Try a much bigger value here as well and check that the limit still holds. Then bring it back down and play a normal fight. Staying under the cap doesn't tell us whether the effect is balanced. Okay, we've got item effects to choose from. Now let's put some choices inside the rooms and add abilities that we can choose when to use. What if the card that we want never shows up? Let's say we've got Ember Brand, the card that makes enemies burn. Well, now we would want Storm Coil, the card that jumps to damages to nearby enemies. After every room we get three cards and Storm Coil would never be one of them. So what else could give us a choice? Well, one option would be a shop. Enemies drop gold, obviously, is the currency that we would spend there. We walk up to an item on its stand called a pedestal, check its gold price, and press F if it's worth it to buy it. We can buy all three offers if we can afford them, just like a regular shop in most games. Now a treasure room can give us three items for free, but taking one makes the other two disappear. Now this generally makes sense. An altar room can offer us two items, but taking one will lower our maximum health. The offers are still random, so Storm Coil might not be there either, but either of those rooms is another chance to find it and each one has its own rules for what we give up. Why do we have gold and essence? Couldn't one currency pay for everything? Well, it could, but then buying a sword now would also spend money that we could have used on a permanent progress. So here, gold pays for the runs' shops and essence stays saved for our future unlocks. For this project, separate currencies let us tune those two choices independently. All right, we will now want to finally work at the shops and inventory and gold and all that gibberish. So let's open up our game manager because this is where we'll actually register our gold. To do this, we'll add a function at the bottom. Here, we will register gold. This will basically just run the stats. We'll add the stats gold and basically add it. Of course, if we need it. We'll also have spend gold, which is very similar, but obviously it spends it and gets it rather than actually changing anything, per se. Uh but it will obviously change the gold stat if we have it. But it'll only do that if we have enough. So, uh if we don't have enough, we'll obviously return false. A coin might overlap the player more than once before it's removed. We still only want to award it the gold once, though. So, we'll check a collected flag and set it before giving the reward. The base pickup script handles movement and contact, and gold pickup defines what the this pickup gives us. It's the same inheritance idea we used for the enemies. We'll also roll the enemy We'll also roll whether an enemy drops a coin. A 55% chance applies to each defeat. So, a short test can drop no coins. To test collection, spawn one directly so we aren't waiting on that roll. Next up, we want to create a new script called pickup. This will allow us to pick up items. So, let's create a new script. I'll pop this into the scripts folder called pickup.gd. Hit create. And in here, we're going to go ahead and I'm actually going to let you think. What do you think we should have this extend? If we have a item we want to pick up that is basically we go on it, it gets destroyed, and it goes into our inventory. What sort of node do you think we should extend? Hopefully you paused the video to think about it. And that is an area 2D. It's super simple. We basically just want to add a magnet radius. This will allow us to have automatic pickup. We'll have a speed, which is going to be pretty high because having an item slowly come to us is pretty lame. So, we'll have it come to us really fast. Uh we'll have a velocity, player, and collected. We'll have a ready function. We'll connect the on body on body entered function. We'll have a function toss which will set our velocity. Then of course the important part which is the physics process where we'll actually move our coin towards our players. We'll get access to our player first and then we'll set the velocity with move toward. And we'll basically look for the player and the distance to the player and we'll just go towards the player using the global position. Because this is a area 2D, it doesn't have a built-in velocity. So we need to use the position. Once we've done that, let's go ahead and fix that error at the top by adding in our body entered function. This will simply allow us to check to see if we connect with the player and if we do we'll queue free collect equal true and set collect body. Now this one for now what we're going to do is we're going to have a sub class override. So basically we'll change the collect depending on what sort of pick up this is. But to do this we need to go ahead and make the function and we'll just have it pass for now. Now we need to actually make this scene. So let's go ahead and create a new scene. If you want you could actually just duplicate the weight slash wave and go from there. But it's always good practice to I guess practice in this case. We'll go ahead and create a new scene called gold pick up. We'll add a collision shape 2D as a child and of course a sprite 2D. We'll go ahead and zoom in here and give this a circle shape. Now surprisingly there's no built-in or preset coin. So what we're going to do is just find some sort of um thing that we can actually just use as a coin. In this case I'll just use a potion for the coin. Uh and then maybe what we can do is go to visibility and we'll just paint it uh we'll paint it gold or self modulate. Or for the modulate that's the important part. Uh and that's it. So, let's go ahead and rename this to gold pickup. We'll save this in our scenes folder. That's perfect. Now, for the uh, area 2D, we want to go ahead and go to the collision. For the layer, we're going to go to eight because this is a pickup. Unselect one. And then mask two because this needs to connect with the player. So, the player body. And that's it. Now, we go go we need to go ahead and add our pickup. So, let's go to our script here. And connect our pickup script at the very bottom right or just connect it to the node itself. Now, you might be wondering, well, how do we really change this because the pickup or collect doesn't really do anything? That's very good question. So, to actually solve this, we're going to detach the script and we're going to create a new script called gold pickup. This needs to go in our scripts folder. And this one This will be very simple because all we're going to do is extend the pickup. Now, the the pickup extends off of area 2D. So, we don't need to actually set area 2D inside of this script because it's already set. Now, all we need to do is override the collect function, which is super easy. We just simply need to add the collect function and this will override the pickup function. And then from here, we'll register gold with the value of one and we'll play the pickup sound with -3 decibels. Okay. Now, inside of our room controller, we want to go ahead and load that scene. So, we'll add the gold pickup with the gold pickup scene. We're going to add an on ready variable pickups. So, make sure you have the pickups uh, node here down there. And then back inside of our script, we're going to go ahead and add a function at the very bottom called a drop gold. This will literally just create a bunch of gold and then toss it around a specific uh, random range basically. So, we'll allow our player to have gold get dropped whenever I call this function. Inside of the enemy defeated, this is where we'll actually create the coins. So, to do this, what we can do is every time an enemy gets defeated, we'll basically roll a coin or a die, I'll say, that's basically 55%. I think 55% is a pretty decent number. Um and then from there, we'll simply drop the gold at a global position of the enemy with a random range of 1 to 3. And then obviously enemy needs to be underscore enemy. And that's it. The all lives stays the same, uh but the drop gold is right there and that's it. It's pretty simple. We're basically just rolling a percentage and every time it's an enemy's defeated, this gets rolled. And we drop anywhere from 1 to 3 coins. Now, to show this, we need to go ahead and head over to our HUD. So, we'll go ahead and go over here to the on ready. We'll go on ready uh gold label, which we need to add in just a second. Uh but before we go and add that, we'll just go ahead and inside of the process function, we'll make sure we update it by saying gold label.text is equal to the actual gold uh where we run the stats of the gold. And that's it. But now, obviously we need to make the gold label. So, let's go ahead and head over to the HUD. We'll go ahead and I'll duplicate the tier and rename this to gold label and make sure we move it down just a little bit so we don't have overlaying things. Uh so, you can do this and then maybe I'll put this on the top left. That may make sense uh below all the the bars of stuff. So, this I can move it right there and I think that's good. And now from there, we can go ahead and test it. You can see our gold is being overrun by the other label, so we can actually go ahead and move that down just a little bit, and I think that's good. Now we have zero gold. Let's see if I can kill something, and I got two gold. And there we go. And now I have five. So, you can see that it is being updated, so that's good. Okay, we have coin pickup, but how would you use the same base to make a health pickup? Do we need to rebuild how it moves toward us, or can we just change what happens when we collect it? Take about 2 minutes to think about this, and take another 2 minutes if you want to actually try building it. Keep the base's attraction, contact handling, and collected flag. Change the collection hook so it heals the player. Test it near full health to check the player's health cap, and make sure one pickup can only apply the heal once. Okay, we walk up to the pedestal, but nothing happens. Before changing the purchase code, did its array 2D detect us? Check the shape and collision settings. We'll put the stable parts like the shape, base, and prompt in the scene so we can inspect them. The script can set up the item's specific display, such as its name, color, and price. Building nodes in code is also very valid. It just means that we need to inspect the running tree when checking what was created. All right, we now want to make a new scene here, and we'll extend off a Area 2D to start off with. We'll go ahead and add a Sprite 2D. And then we'll add a Collision Shape 2D, and then the most important is the Label. We'll rename the Area 2D to Item Pedestal. We'll rename the Label to Prompt. And for the text inside of here, we want to go ahead and say press F. We'll drag this uh above the Sprite 2D, which we don't have, so let's go ahead and find something that would match. Um for this, we can kind of use whatever, but I think I'm going to use 0032. Ideally, you make a pedestal that would actually look a little nicer here, but this will work for now. We can put this right above, and for the collision shape, we'll go ahead and give this a circle shape. We'll go ahead and save this as uh item pedestal, but we want to go ahead and capitalize it properly. Save this in the scenes folder. And we're going to add a script here called item pedestal, but we want to make sure this is in the scripts folder. Hit create. Inside of here, we'll go ahead and open up the script. Actually, before we do that, let's go ahead and set the collision for the layer before we forget that. The mask we want to be on two, and for the layer, it'll be eight for the pickups. While this isn't exactly a pickup, it is something that it's supposed to interact similar to a pickup, so this works pretty nicely. One thing I want to note is the radius here needs to stay below 30. So, we can do at most like 28. We can put this right above, and this should be good. Okay. From there, we want to go ahead and open up the script. We'll create a class name and extend area 2D. We'll go ahead and add a couple things we need, so a signal chosen and a couple variables. Uh, we'll have a dictionary, price, HP cost, reroll room. Now, keep in mind that these are basically two different things. So, sometime maybe you can have the cost of both, but in this case, um, we'll be kind of looking for one or the other. We'll also need a prompt. So, we'll load our prompt, and then we'll have busy and a player here. This will start by default, and this will set the set to true when our player is actually interacting with this pedestal. We'll add a configure function, which will literally just set everything. So, once we add this, similar to what we did with the pickup item, we'll have this all get set. For the ready function, we'll connect our signals that we need, body entered and body exited. This is very important because we need to make sure that we know if the when if and when the player enters the area for this pedestal and then exits. For the build visuals, we'll go ahead and show nothing if we have nothing to show. Otherwise, we'll have an orb that which will create. We'll have a polygon 2D that will create, so it's a new object. We'll set the color and position to the rarity and common. We'll add the child to a child of the pedestal, and then we'll create the title with of this thing. So, this is separate to the label that we already have, obviously. And then we'll just add the label, which will basically just show the price or the cost. So, keep in mind that this is an elif statement, so it's one or the other, not both. If you want both, then yeah, you'd have to adjust the code to whatever you want. We'll have to add a function here for the rarity color. So, we'll add a rarity color where we'll return specific colors based on cursed, rare, or not. We'll create a process function, which will allow us to actually interact with this object. So, we'll have a function called take. Obviously, we also will need to set our body entered and exit. So, we'll do this by checking if the player is a body, then we'll set our player here to true and our prompt visible to true, and set it to false when we exit. So, that's very important. And then, of course, we want to create our take function. This will allow us to just set everything to to busy equal to true, prompt is equal to false, and chosen will emit the chosen thing. So, the def will be the chosen thing or prompt or item that we actually choose. Now, we need a thing that will refuse if we fail to buy the item. So, this will literally be that. We'll refuse the item if we can't buy it. So, we'll have a prompt pop up and we'll have not enough floating text and a play click that gets played. We'll also have consume, which is the basically the opposite of refuse. So, if it does succeed, then we'll basically Q free this item and yeah, that's it. We'll consume the item and we'll play the upgrade sound. We interact with the pedestal. Do we just give the player the item? Well, in a shop, we need to charge gold, while a treasure room has different rules. So, the pedestal tells the room which offer we choose. The room checks what that choice requires. In a shop, it checks the gold before charging and giving the item. Whereas in a treasure room, choosing one removes the other choices. At an altar, the cost reduces maximum health. So, it lasts for the run. If we can't afford the purchase, we need to clear the busy flag and show the prompt again. Otherwise, one failed attempt could leave that pedestal unusable even after we got enough gold. Now, inside of our room controller, we want to go ahead and find the on enter room. And we want to now add some more room match. So, from here we're going to add treasure, shop, altar, and we'll need some functions for each one. But first, at the very top, we're going to go ahead and load in our pedestal item, which we just added. We'll also create a stocked variable dictionary and a open stands. From there, we'll go to the bottom of our script and we'll add a few couple functions. So, we'll make pedestal. This will add our configure. So, basically inside of every item that we create our pedestal item, we'll configure each one, we'll add it to the room, and return the pedestal that we just created. We'll have a function that shops price for us. So, this will basically get the actual price that we need and return it as an integer. Then, of course, we also need a place pedestal. So, we'll have the function place pedestal, which will literally just look through our map and add it to the shop. Now, the important part here is the 128 by 128. This was literally kind of what I was mentioning about the radius. This is the important part for the radius, not having it bigger than 30 pixels. Otherwise, each one will be like two close to each other and you just won't be able to have them interact properly or it'll kind of just bug out and the player will be able to enter two pedestals at the same time, which we just don't want. We'll add another function, open treasure. This will just allow us to mark if a treasure not opened and we can yeah, place it. From there, we'll also add on treasure take. This will allow us to actually take the item. Then, of course, we will have the stock shop. Here, we'll have uh the same loop as the treasure with a real price but a different callback. It doesn't save the set because in a shop, you buy you can buy all three if you'd like but depending on if you want it to do that or not. Um but in ours and in most rogue-like shops, you can buy all three if you can afford them. Which usually you can, so but it is usually good to give the option because some players do like to hoard their money. Now, at the top, we're going to go ahead and add a new constant. We'll have the shop bases. So, these are the base prices essentially. And then, going back to the bottom, we're going to add a on shop button. This will basically spend the gold and tell us if we have enough gold or not. And then, this is where we actually refuse if we don't have enough. So, you might recall adding the refuse function but we never called it anywhere. Well, that's where this would be and then the consume would be if this doesn't happen, then this happens, right? So, if we can't afford it, we'll consume it. Now, we also need the open alter function. So, from here, we're going to go ahead and add an open alter function, which will literally just open the alter for us. Now, this one is based on the max health of the player. So, keep in mind that this is a little different than the shop. It's quite literally a alter. So, it allows our player to basically make a decision on if we want to spend health, and that is basically what happens. So, here the health HP cost will get set. We'll connect the signal, which we'll have to create in just a second. And if so, then we place the pedestals. From there, we'll have the think function on alter take that is very similar to what we created earlier, but in this case, we're using health rather than money. So, it's the exact same thing. We'll have the refuse, and we'll have the on treasure take, uh but this one is obviously just health. And then we can set the health with the max health and minus the HP cost. We can see our items in the codex and find more rewards inside the rooms. A coin sets its collected flag before giving us gold, because another contact shouldn't pay us again. A pedestal works differently. It tells the room what we chose, and the room checks the rules. A shop charges gold. Treasure removes the other choices, and alter costs maximum health. But what if we can't afford the shop item? We still need to clear busy, and show the prompt again. Or coming back with more gold won't help. Try that sequence now. Fail a purchase, earn enough, and return. Then press quickly twice and check that we bought it once. So far, most items change something that happens automatically. But what if we want to choose something when an ability happens? We'll store an equipped item action. Give it a button, and check its cool down before running it. Pulse affects nearby enemies. Phase moves us a short distance. Siphon needs a living target. So, what happens if we press Siphon with nobody nearby? Well, in this version we'll give the cool down back when no target is found. That's a choice in our implementation. So, we'll test it alongside a successful one. Now, from there we will need to go ahead and head over to our player controller. And at the bottom here we'll add a couple new variables. We'll have active item, active name, active cool down, active cool down timer, and then phase timer. At the bottom we're going to go ahead and add a new function, set active item. This will allow us to actually set an item to be active. Well, we'll basically just set every variable to active active item is equal to ID, active name equal to display name, etc. So, we'll just pass through these variables. From there we'll have a handle active input with delta being passed through. This will literally just allow us to detect things that we want. Now, in order to actually use all these, right at the update aim inside of the physics process, we'll add a phase timer that gets set, and then we'll also right below the handle attack input, we'll call in the handle active, and we'll also have the sync invulnerability. Now, the sync invulnerability is something we don't have, so we're going to need that. And that is because inside of the start and end dash, we have the invulnerable being set. Now, inside of the end dash, we're going to go ahead and delete this, but instead we're going to have the sync invulnerability function being called. Now, before we forget though, we need to go ahead and head over to our upgrade manager and add all those new items that we're going to need, the forge pulse, phase step, and blood siphon. Phase step is going to be the important one here for the invulnerability. And then near the end of these functions, we'll add all the things that we'll need. So, apply pulse, phase, and siphon. So, this will just set active item for each one that we just added. And then heading back inside of our player controller at the bottom, we're going to create the use active function that we'll have. We'll basically set the forge pulse phase step for everything that we need. Obviously, each one of these needs a function, so let's start with the forge pulse. The forge pulse will basically set a ring with our juice. We'll get the world obviously with our current scene. And inside of the enemy, we'll simply take it'll take damage, and that's it. So, it's pretty simple. We're just finding the enemies within the groups. We look for them, anything within a distance of 140, and then they take damage. We could make this phase at a distance straight to the player's position. But, what if there's a wall in the middle? Now, we've jumped through it. Test Test to move lets us check how far the body could travel along a path before we actually move it. The kinematic collision 2D object stores the result. It isn't another shape. If the path is blocked, we'll use the permitted travel. Otherwise, we'll use the full step. We also need to combine our invulnerability checks. If the phase window ends while we're still dashing, that shouldn't turn off the protection while we still get from the dash. For the phase step, because this one is similar to a dash, we're going to create We're going to get our mouse first. Then from there, we're going to test the movement and sweep the player's actual body along the motion adding 130 pixels directly would teleport straight through the walls and locked gates, so we don't want that. We want to actually make sure we test it, and then we will say our global position plus equals motion. And we can do that obviously using a built-in function called test {underscore} move. So, it's actually very useful. Now, from there uh finally, we're going to get rid of this error for the sync invulnerability and by actually adding it. And it's very simple. We'll just simply return or not return per se, but set our invulnerable to not health is alive or is dashing or if the phase timer is bigger than zero. So, this is a true or false basically. It's kind of checking to see if this is true, if this is true, or if this is true. Um Okay, and then our last one is our blood siphon, which is one of my favorites. It's basically going to do a very similar thing to the other function where we had the uh forge pulse, but we're going to basically get to the enemies within a distance. We're going to find it. And if we don't have a target, then we'll check to see if we don't have a target. And if we don't, we'll just return and say no target. Uh but if we do, we'll say we'll take that best thing and it'll take damage. It'll give it the before. We'll heal, so we'll siphon. So, that's what the blood siphon means. So, the monster takes damage and then we'll heal ourself. And then we'll set some floating damage and it basically shows the damage that we did. All right. Now, inside of the room controller, we want to go ahead and find the open floor or enter floor function. Now, before we generate the new room right here, we're going to go ahead and for loop and basically queue free all the coins. Once we've done that, we also now want to clear the stock and clear all the open stamps. Once we've done that, the the enter floor is now done because we're going to be clearing everything before we actually create it. And that is good. All right. From here, you can go ahead and test and make sure everything is working properly. But obviously, make sure we go ahead and save. >> We have five gold and try to buy an item that costs eight. Later, we come back with 10. What should happen to the first attempt and what needs to happen to the paddle stools busy flag? The failed attempt shouldn't change our gold or give us the item. It needs to clear busy and restore the prompt so we can try again. Then the successful attempt should charge and apply the item once. Try pressing again quickly to check that it doesn't happen twice though. Okay, what happens if we make one upgrade much stronger than intended? Try it in a copy of the project and if it causes a problem, can you limit that problem without making the item pointless? Give yourself about 15 minutes here. Write down the condition that caused the problem so you can test the fix against the same case. For example, healing on every hit could become much stronger with a fast attack. You could compare a lower heal amount with a limit over time. Those produce different results. So, test slow and fast attacks with both. Keep the change that addresses the behavior that you wanted to limit here. Then restore the intended item value before continuing. If you're wondering what to build after this, Coding Quest puts the systems into a path that you can follow toward a game. You write the code and check the work as you go. I have a bunch of free quests to start with, so use the link down below to try a task on your own level. There's a lot more in each floor now. Before we build retry, let's make sure that leaving a floor removes the things that belong to it. Okay, our game has a lot going on at once. Monsters, upgrade cards, gold, shops, and items, and and a new floor every time we beat a boss. Before we build what happens when a run ends, we'll start this chapter with a checkpoint. A few pieces we built earlier don't quite agree now that they all meet. So, we'll fix those first. Starting with the capital letters in our file paths and what's left behind when we change floors. Then we'll come back to the HUD, the health and dash bars on our screen, and make lower health impossible to miss. It's quickly worth mentioning here that as mentioned in previous parts, when I added these here, these need to be capitalized. So, in Windows it will be ignored, but in other places like Windows or Linux and Mac, this won't be ignored, so make sure the case sensitivity is correct. So, in the HUD, in the weapon controller, and the room controller, at the very top, make sure that the scenes are all case capital. We'll also be replacing the ready function with I trust the first three lines, so we'll be removing the last two lines because we will be adding a game manager start run later. So, we'll go ahead and just delete those last three lines. We leave the floor, so the old enemies need to go. Can we just run their death code? Well, that might give us gold or announce that the room is cleared. We're cleaning up here, so removing these enemies shouldn't count as defeating them. It's a little different, obviously. So, we'll disconnect the defeated callback, remove the children from their containers, and queue them for deletion. We'll also clear the player's leftover movement before placing them at the new entrance. Then in on the very bottom of the room controller script, we're going to go ahead and add clear floor container. This will for loop it through all the containers and all its children and basically disconnect everything, remove all the children, and queue free. Then inside of the enter floor function, we're going to go ahead and add that. So, clear floor containers with enemies, projectiles, and pickups. Now, the projectiles, we never loaded that as a variable. So, we can simply just get node immediately inside of it, and that's it. Similarly, inside of the player controller, we can add a new function at the very bottom called reset floor motion. This will literally just reset everything, uh resetting all the is dashing timer, etc., everything to its default value, basically. And then back inside of our room controller, right before the gold drops right here, so right before here, at the top of this function, we're going to go ahead and add a safety check and basically check to see if things aren't valid. If they aren't, then we'll simply return. Now, a small mistake I made previously was inside of the grunt enemy, we need to make sure that that is using the grunt enemy. Now, this was correct, but the caster enemy in this script was actually also using the grunt enemy. We need to make sure that loads the proper script. And then funnily enough, I actually basically use switched the scripts accidentally. So, the grunt enemy was basically the caster enemy. So, I need to go ahead and just copy paste everything inside of the caster here, and then all of these all go into the grunt enemy. Now, if you already had everything correct, that's good. I just basically made a small mistake. Inside the caster enemy, you'll know that it's correct because the projectile is in this scene. Okay, the caster needs the normal corruption changes plus a change to its own attack. So we override that function. But now did we keep the base behavior? Not automatically. Our override replaces the method unless we call the base version too. So we'll call super dot make corruption first, then add the caster's chain or calls the base implementation. Calling the same method on self would call our override again and make keep repeating. We want the shared corruption set up once followed by the caster specific part. Now inside of the projectile enemy, we want to go ahead and create a new function here. It has to go anywhere below the ready function and we'll simply say make corrupted. This will allow us to make the caster enemy corrupted at any point that we want. Then inside of the ready function, we can do this maybe right below the on ready. We'll set the scale of the sprite to the sprite scale. Next up, we want to find the key right here and we basically want to add a type node right before we set it to player. This will keep a guard for 6.2 when we actually get to that. Oops, sorry. We need a colon and then node like that. There we go. So P and then the colon and then node. Okay, we're dodging an attack. What do we need to see it right now? Health and whether the dash is ready. Out of shop, gold matters more. Between fights, we might open the codex to read an item. So when does each piece of information actually help us? It gives a way to decide their size and placement, Then check whether the information we need is easy to find without covering the fight. All right, from here, we want to go ahead and head over to the stat bar. And I want to go ahead and just basically remind you of the ghost stuff because this is where we're going to be start we're going to start changing things. Now, let's say we take a big hit. We're watching the enemy, not the health bar. So, how much did we just lose? Well, our health bar has a second darker fill behind it. When the hit lands, the bright fill drops straight away. And the darker fill follows it a bit more slowly. The gap between those two fills shows us how much we took in terms of the hit. We can change how fast the darker fill catches up. If the catch up is too fast, we miss the gap. If it's too slow, the dark part starts to look like health we still have. When our health drops below 30% of its maximum, the whole screen can pulse red. And then we can pulse it a little faster the closer we get to dying. Now, that pulse has to stop when we heal back above 30%. Otherwise, it keeps telling us we're in danger after our health has gone back up. So, closing this, we're going to go ahead and open the HUD. I'm going to close right here. And we're going to add a new node here called color rectangle. I'm going to add this. And this is going to be a full rectangle. And now everything is is white. Now, we don't want that because we want to basically remove the alpha. We'll set the alpha to zero, and we also, very importantly here, we need to go to the mouse and set this to ignore. This is very important because if you don't do that, this will block your mouse input. This is a very, very common mistake that a lot of people will do is having this on top of everything, and now we can't click anything. This happens with almost any control node, so keep that in mind. Uh so, okay, after that, we're also going to rename this node to overload pulse. Then, back inside of our script here, inside of our HUD, we're going to go ahead and load that node by getting on ready variable. We'll create a new variable called time. We'll also create a variable called game over and then leaving. Inside of the process function, we're going to say if game over or leaving or if paused, return. Then we're going to have our other check of player then return. One more check here is going to be if player is null, then we'll return. Uh but before we actually do that, we want to check to see if the uh we actually have to do this first, sorry. This needs to go before this check. So we get we have to set the player before we actually check to see if it's null. That would make sense. Then from there, we have all the health bar stuff happening all the way until the gold bar. And then lastly, the pulse itself. This is the fun part where we actually add the pulse. The basic idea here is we're going to get our player's health. If it's below 0.3, basically 30%, then we're going to pulse the color. This is basically going to take the color of the thing that we just added, the color rectangle, and pulse it red back and forth with a sign and that's basically it. And this is a very cool small addition that we can add to the game. There's better ways of doing this, but this is a very simple way of doing it mathematically essentially. Now another thing we need to make sure is that inside the ready function, we have this line right here. Because we need to make sure that it is always pulsing. All right. And from there, we're pretty much done. You can go ahead and test the pulsating stuff inside of our game and see how you how you like it. >> Okay, I want you to pick one HUD element and try changing its visibility, size, or position. Give yourself about 8 minutes here. Play a fight and then check a reward or shop. When did you need that information? Was it easier to find after you changed it? If you hide an element, check whether another screen still gives you the information when you need it. If you add one, check that it doesn't cover enemies or warnings. There's no required number of HUD elements here. This is very dynamic and just up to you. Keep the version that helps with the decisions you're making in those tests and compare it with the original before settling on what you want. We can clean up a floor now. Now, what happens when the whole run ends? We need to decide what resets and what we're keeping. Now, when we die, the game ends the run, shows our results, saves the essence, the currency, which is the currency that we keep between a 10. And it gives us a way to start again. A message saying you died and a retry button would get us back into the game. But on its own, it wouldn't show how the attempt went. The game is split into floors, each with several rooms. Our summary can show which floors we reached, how many floors or rooms that we cleared, enemies defeated, and how long the run lasted alongside the other fight statistics. Now, those give us something to compare every one number our death screen will show is the best combo. A combo here is a chain of kills. When we defeat an enemy, the chain goes up by one and a 3-second timer will start. If we defeat another enemy before that timer runs out, the chain will just go up again and the timer will start over. If the timer runs out or an enemy hits us, the chain drops back to zero. So, we'll store how long that window is, the chain itself, and the time left on it. Every kill adds one and refills the timer, and getting hit will break the chain. All right, we want to go ahead and open up the game manager script and pop it out. And at the very top, we're going to go ahead and create a new constant, combo window. We'll also have two new variables, combo and combo timer. Now, at this point, we need to go ahead and add a function process. This is where we'll basically control the combo timer. Uh very simple, we'll just check to see if it's bigger than zero. If it is, we'll reduce from it, and then once it's uh less than zero, we'll make it zero. Now, we need a function to register kill, so we can go ahead and do this at the bottom or around the register functions could make sense. So, right here, we can go ahead and register kill. Here, we'll basically add to the combo. We'll set the combo timer equal to the combo window. And we'll take the stats score, add 10 to it, and then take the max combo inside of our stats and set it to the max integer of the max combo and the combo. From here, we'll go ahead and add a break combo function. This is literally just to reset everything. We press retry. What should we keep? Our banked essence and permanent unlocks. Sure. But, if we keep all the gold and temporary upgrades, too, we aren't really starting a fresh run. So, those two kinds of progress need to be separate. Start run explicitly resets the run values. Pause state and time scale. Reloading the scene won't reset that in an autoload because it stays alive across um scene changes. Once the new player is created, it can read the permanent unlocks and apply the starting bonuses once. We'll check each value as we add it, so we know whether it resets the run or survives it. Then, below the spend gold, I'm going to go ahead and add a start run. This will allow us to take our uh basically set everything to the default values. So, our hit stop token will be plus equals one. Uh we'll set our paused to false, reset everything, duplicate the run stats, uh basically just set everything that we need to the default values. From there, we'll go ahead and also create a get run time function, which return a float. It'll return the max float of our get tick with our time and our run stats with started MS. Now, from here, we need to go ahead and call this function, the start run. We'll go ahead and do that inside of our room controller. Inside of our room controller here, we can go ahead and add this in our ready function. We can add that at the top. Now, inside of our player controller, at the very top, inside of our ready function, we're going to go ahead and add a new function, hurt box connect on hurt. Now, we need to add that function by going to the bottom or anywhere you want and adding a new function, on hurt, which will basically be to break the combo. And that's it. Okay, we lost, but did we get farther than last time? Did we clear more rooms? Did we get better combos? The summary can show those tracked values, so we have something to compare between attempts. We'll also show the essence that we've banked. Those numbers need to come from the runs tracked values, and the banking needs to happen once Opening the same screen again shouldn't award the progress a second time. From here, we're going to go ahead and add a couple things to our HUD, cuz we want to add a way to restart the game. So, first let's add a game over node. So, this will be the control node as the base. From here, we'll go ahead and give this a full rectangle. We'll make it's uh process to always true. We'll go ahead and add a color rectangle. So, I'm actually going to copy this right here. But, this one is going to be full black. And the alpha is not going to be completely uh zero. It's going to be around anywhere you want, but you basically want it to be somewhat transparent, so you can see the background. Um a good base can sometimes maybe be like 0.7, anywhere from 0.5. I like around 0.5 just cuz it makes everything a little darker behind it. From there, we'll go ahead and add two more labels and a button. I'm just going to copy this uh one of the buttons here. And now to rename everything. The this one is going to be called backdrop, summary, essence, and retry. For the retry button, we need to go ahead and set the text to run again or whatever like retry, whatever you want. For the essence label, we want this. Why is it all the way over there? Let's just make sure all our other labels are in a proper place. Okay. For these ones, we're going to go ahead and set the essence. I'm going to go ahead and write test here. And basically move these two the center area. Uh you can go ahead and center it yourself, but this seems pretty decent. Uh make sure the essence label is below the summary on its own, and that's it. From here, uh I'll actually move the summary up a little bit. Um but, that's it. We basically have a text two different labels where we can add these two things. All right. Now, from there, we need to go ahead and add these variables into our uh HUD script. We'll load in the game over and game over summary. So, make sure that those are both correct. From there, we'll also load in the essence. Now, at the very bottom, we want to go ahead and format time. This will basically just return a string with the time. So, we'll take a look at the seconds with we'll pass through seconds and we'll pass through the time and basically load in minutes and seconds. Our active item checks its cool down and any target it needs before using an ability. Phase also checks the path, so an instant move can't put us through a wall. And if phase protection ends while we're still protected by a dash, we need to keep that other protection. Then, we leave the floor and clean up enemies, projectiles, pickups, and leftover movement. Removing an enemy, there isn't another defeated. Now, we're deciding what happens when the whole run ends. Temporary gold and upgrades should reset, while permanent progress stays. Reloading a scene won't reset the auto loads for us, so we need to make the those reset ourselves before starting another run. Two enemies hit us almost together and both calls reach the running end code. Do we want to bank the reward twice? Well, no. The first call sets game over and the second returns when it sees that we're already finished. We can wait briefly for the death effect before pausing the world. That wait needs to use real time if we've slowed the game down time. Afterward, we'll check that the current screen and run are still the ones that we started with. If the player has already retired or left, the old the old wait mustn't pause the new game. From there, we need to have a show game over uh script or sorry, function. Um it's pretty simple. All we need to do is basically return if this isn't valid, which is pretty which makes sense. Meaning it's already true. Uh once we do that, we set it to true, so we don't repeat this. We'll create a dictionary with our stats and then we'll load in the stats. So, we take our summary text and load in everything we need. The floor, floor rooms cleared, enemies killed, max combo, the typical things that you generally see in roguelikes like this. From there, we'll go ahead and have how many essence we banked. We'll set the upgrade panel and the codex to false. The game over will be true. Now, for the victory, will you obviously use that in 7.3? Uh so, we're al- almost there, like about three more lessons. And from there, we'll go ahead and create a timer for 1.2 seconds. Then, we'll go ahead and just unset the or set the game to paused equal true. Now, obviously, inside of our ready function, we need to go ahead and set this up. So, we need to go ahead and set our visibility to false by default, add our retry button uh by connecting retry. Now, we have an error because we don't have the retry button, so we need to go ahead and add that. This is basically literally to retry the the game, where we basically reload the current scene, and that will basically reset everything. Uh the reason this works so well is because we already added inside of our room controller everything we need inside the ready function. So, as long as we just reload the scene here, then it works per- perfectly fine. Now, we do need to set up some things in our player because obviously, we need to know when we're dead. So, at the top here, we'll go ahead and add a dead function or variable, sorry. In our ready function, we will add a new button on died. This one is very simple. We'll simply set everything to zero, basically resetting everything. So, here, we'll check to see if if we're already dead, then return. Then, we'll set dead to true. We'll set is dashing to false, set the velocity and knockback to zero. We'll set our vulnerability to true. Basically, just set everything to false and reset everything on the player, basically, and stop the player from actually doing anything. And then, the most important part is to actually show the game over from our game manager HUD. >> Now one important note here is the this line right here, we're going to copy this inside of our physics process function. So right here, we're going to go ahead and add this to the line so that way we return as long as uh actually this would make sense if we add this first. There we go. So that way we return and not do any of this if we're actually dead. And then similarly inside of our room controller in our physics process right here we're going to go ahead and add a new line of guard basically that is the exact same thing um but this time we're going to check to see if we're valid. Uh not only that but we're also going to check to see if the player is alive. And that is very important because obviously if our player doesn't exist or if he's not uh alive then the set up room stuff should not happen. Okay, we earned some essence and it's still there when we retry. Great. But what happens when we close the whole game? Anything we only kept in memory in the game is just now gone. So we'll use config file to write the the values that we want to keep. This will basically help us save outside the game. It's grouped by section and key. Set value changes the config in memory. And save writes it to disk. We'll save under user colon slash slash which is Godot's writable user data location. Res points to project resources and isn't really a reliable save destination in an exported game. On a first launch there may be no file. So we'll keep default values. Then we'll close and reopen the game to test that saving works. Right now at this point we want to go ahead and create a new script called the meta progression. This will literally save our progression by creating a save file. To do this, we first need to create where the save path will be. From there, we'll go ahead and add a total essence unlocks dictionary inside of our ready function. We're going to go ahead and load the game because this should auto load before anything else. Now, obviously, we don't have the load game function, so let's go ahead and add that. Basically, we'll get our total essence or unlocks, we'll get our CFG, our config file, we'll create a new file, we'll load that file in or sorry, we'll check to see if it's loaded is not okay, otherwise we'll return, meaning there's no save yet. Then, from there, we'll basically just fill everything in. That means we have values that we can actually fill in, so we actually use those. From there, we also need a save game function. Now, this one is a little bit more complicated, but the basic idea is we're going to create a config file, set the value values of meta essence and unlocks with the unlock and total essence, which we have saved over here. And that's it. We just need to save it by setting our error to the save.config save. Uh from there, obviously, we want to check to see if it it does error, and if it does, then we'll push an error, uh but other than that, there's no big safety check. We're just going to push an error just in case. And from there, we're going to go ahead and add a bank run. This will basically just add our total essence and then save the game. Now, inside of our HUD, we're going to go ahead and head over to the show game over function, and we want to go ahead and right under the game over, we want to uh call this. Now, obviously, we had the issue, which is that this script needs to be auto loaded, so let's go ahead and head over to the globals, auto load, select script, scripts, pop in our meta progression like that, and hit close, and eventually, this should go away. If you want, you can go ahead and reload the project by going to scenes and reload saved scene or reload Sorry, project and then reload project. Yeah. All right, from there we're going to find our room controller. And inside of our room controller, we're going to pop it out. Inside of the on enemy defeated, we're going to add a couple things here. We can add it at the very bottom, but basically we'll register a kill in our game manager, we'll run the stats here. We'll also set the essence by adding one. And then the last part is is if if is corrupted in enemy and if enemy is corrupted, then we'll add three essence. Now, enemy it should be underscore enemy, so let's make sure we actually have it as underscore enemy. Now, the last part or not last part, there's a little bit more to go, but in the HUD, we want to go ahead and find this line right here. We're going to go ahead and replace this with a count up function. Now, obviously we need this count up function, but this will work a little better with our current essence. Here, we'll basically get a tween and it'll tween the text, so that way it's a much smoother count up rather than just setting the number or setting the text. Um this basically just makes things a bit smoother. Okay, and that's pretty much it. You can go ahead and test things out if you'd like. Okay, we finished a run with banked essence and a temporary damage upgrade. What should survive retry? What should survive closing the whole game? And which test tells us that the save file worked? Well, the banked essence should survive both for sure. While the temporary upgrade resets with the run. we need to close and reopen the application to check the file. Retry alone might still be reading values from an auto load that stayed in memory. What would you want to know about your last run? Add or improve one summary stat, then work out exactly which events should change it. Give yourself about 10 minutes to do this, then run a small control test where you know what the result should be. Let's say that you track damage taken. Take one hit where you know the damage, then end the run. Does the summary show that amount? Now retry and finish without taking a hit. It should be zero, or we're carrying something over from the last run. You can do the same kind of test for rooms cleared or a combo. A number can look reasonable on the summary and still be counting the wrong thing. We can save the essence that we've earned. So, what can we spend it on? Let's give the hub some permanent up unlocks now. Now, for permanent upgrades, we spend essence, the currency that we keep between runs. Imagine a shop that adds five to our health limit or five to our attack damage and lets us buy those upgrades again and again. Our actual between run shop, called the forge, sells four permanent upgrades. Each can only be bought once, though. One can be called twin fang, which is basically a pair of daggers. Now, the other three raise our starting health, a quick attack damage, and movement speed. Now, each button shows the unlock price, and once we own that unlock, the price turns into a tick. The button greys out when we already own the unlock or can't afford it. All right, so we want to head over to the meta progression and add a couple things that we're basically going to add as upgrades. These are going to be permanent upgrades, that's why it's going to be inside of the meta progression. Basically, we're going to add cost and names. Okay, we disable the button because we can't afford this unlock. Is that enough? Well, the purchase function could still get called another way, so it needs to check the purchase itself. Does the ID exist? Do we already own it? Do we have enough essence at all? Once those all those checks pass, we'll subtract the cost, mark it unlocked, and save. The next player we create can read that and unlock and apply its bonuses. We need to do that once for a fresh player because repeatedly adding the same bonus would keep increasing the stat. We'll test that the purchase survives a restart and that another run gets the same bonus rather than a larger one. Then, at the very bottom, we're going to go ahead and add a couple functions. We're going to add cost, which is just going to return the cost of something. It's going to return this number if it's not in the table, basically a typo. Um things like this are always good to have just in case. Uh and then similarly to is unlocked, we'll have false by default, meaning if it's never written, then we'll have a can buy, which just returns a true or false, basically telling us if we can buy it. And then lastly, which makes the most sense, is buy to actually buy the item. We'll use the total essence that is inside of the meta progression, so we don't actually need to call anything crazy. We already have everything we need inside of the script. Which is basically why we're adding it to the script. Okay, now to make these work, we need to go ahead and head over to the weapon controller first. We'll go ahead and add a new function at the very bottom called the set available. This will return void, but it's going to take our available weapon and duplicate it. It's going to replace the weapon list, resetting the first slot because the old index may not exist in the new list. An unlock should give us more starting health, or it could give us another weapon to choose. Do those change the game in the same way? Well, not exactly. One changes a starting stat, and the other adds an option that we still need to balance. Our vigor upgrade adds maximum health, while toned adds quick attack damage. We'll keep those effects consistent with the button descriptions and apply them once when the new players start. So, inside of our player controller, we want to go go and add at the very bottom, apply meta unlocks, and there we go. No no errors. The basic idea is we check to see if something is unlocked, and if it is, we change our stats. This happens basically every time we run the game, so you can imagine this function needs to be called at the ready function. We can add this at the very bottom here. And that's pretty much it. Now, we want to go ahead and create our hub, because right now we only have basically combat room and all that stuff. Uh but we not we now want to create a new scene. We'll call it hub, but the uh first part will be a control node. We'll go ahead and save this as hub inside of our scenes. Save, and you can see it's already a full rectangle, which is perfect. That's what we want. We want to add a label, a VBox controller, or container, sorry. For the label, we're going to call that essence. It's going to show the essence. Inside of the uh controller, or the VBox container, sorry. We're going to go ahead and duplicate a button four times. And then one more time, but this one is going to be outside of the uh VBox container. For this button, this is going to be the start run button. So we can go ahead and rename this to start run. We can literally just have the text be start run, but with a space. The VBox controller will be called a unlocks. This will be where all the unlocks are. We can go ahead and kind of drag this to the middle. This button will be daggers. The second one can be vigor, honed, and then swift. You can obviously rename these to whatever you'd like, but that's pretty good. Um for each of these, we can go ahead and set the text to the same thing as the word or the name of that button. So we can say honed, a swift, etc. So dagger, vigor, honed, swift. For the start run, we can move this to the bottom here. And for the essence, we We go ahead and move this maybe to the top right Uh kind of here. That's totally fine. We can say something like this just to see the text. We're actually going to fill this in later, so don't worry too much about it. Now, one thing we want to change before we continue here is inside of our game manager, we want to check at the shake camera function. Now, here we want we want to do is we want to change this so we check if the camera is valid and then if it has the add trauma function. Okay, now inside of our hub, we're going to go ahead and create a hub script. We'll go ahead and add this to our scripts folder, not our shaders. There we go. Then we're going to go ahead and load the essence label. Okay, we've got a button for each unlock. Do we need a separate purchase function for every button? The checks are all the same. We mainly need to just unlock was clicked. So, we'll bind that ID when we connect each button to the same handler. When a button is pressed, that ID is passed to the handler. In this version, we find the buttons by node name. So, those names need to match the IDs exactly. The I The visible button text can say something else. Changing the label shouldn't change which upgrade it buys. But renaming the node means that we need to update the lookup as well. We're going to go ahead and add a ready function, which will allow us to connect the uh basically every button will be able to do this pretty easily by for looping the ID inside of the meta progression cost. We'll connect it with the ID. Now, the way this works is the name has to be the same. So, here you can see that the names IDs are always the same. So, if this isn't the same, this function that we just wrote will not work because it's basically connecting with the name that we just added. Uh but obviously that is only depending on if inside of the meta progression cost you wrote these the same with the names. Okay. We'll also have a refresh function. This will literally refresh everything. This one will basically refresh the essence. It's kind of to call it once we buy something because then we want to actually make sure we bought something, reduce the essence, update the essence, uh etc. We also want to make sure that the buttons are set to enabled or disabled if we can buy them or not. We'll have a cost next to them as well. And then for the buttons on the unlock pressed, we will have basically buying it. This will connect it to every single button and every time you press something, it'll buy that ID. So, the meta progression will buy the ID with it with the string and then play the upgrade sound and then refresh which we just wrote. Okay. Now, what we want to do is a way to get here because from our HUD, we don't have a way of getting here. So, what we can do here is duplicate the retry button. Uh name this forge. And then inside of our HUD script, go ahead and open this up. And basically we're going to allow this to take me to the uh hub scene. Now, this scene is normally in the res folder. So, what we can do is move this to our main res folder just to stay where it's a more organization thing. It's depending on how you like to see it. If you don't like that, then you can obviously change the scene path. But before we continue, we do need to also connect the button for the game over forge button. So, we connect that script that function that we just created. And that's it. Now, we have the hub completely working. You can see here we have twin fangs. I can't afford any of them, so they're all disabled. Now, the start run function doesn't work yet, but we will be working on that very soon. Don't worry. Now, one permanent health upgrade can be called vigor. It raises our maximum health, the most health that we have, by 25. A fresh player starts with 100, so buying it raises the limit to 125. Now, that can let us survive for an extra mistake and see more of a fight that we're trying to learn. But, imagine a version where we can keep buying it. The enemy stays the same, while every few losses lets us add more health and more damage. Eventually, we might just be able to take those hits we used to need to dodge. Some games can reward that. They give that. But, for this one, we still want reading the attacks to matter. We want the skill of the player to translate into the next run. Now, the forge, which is our in-between run shop, limits each purchase to only one. We can purchase vigor, but we can't keep adding another 25 health. Now, buying vigor, our permanent health upgrade, and applying its bonuses are separate steps. The save records that we own it. Each new player reads that once when the run starts and adds 25s to its max health. So, we can check both. We open the game and vigor should still have be owned. Then, start a run and check that the player has 125 max health. Check again after going down a floor and again after pressing retry. If we ever have see 150, the bonus is being added twice. Man, that's a bug. Once that works, we compare the starting player with a fully unlocked one. So, does the stronger player still need to watch the warning? Do they still need to pick a good moment to attack? Because each bonus can only be bought once. We can test the player with every bonus unlocked. If the fights become too easy, we can reduce those bonuses. >> Now, twin fangs is a permanent unlock for daggers that hit faster than the sword, but they do less damage per hit and have less reach. We need to compare the two weapons to see if the daggers are better in every fight and buying them has mostly made us stronger. Look for situations where we'd want each weapon. Does the sword's reach actually help or can the daggers fit more hits into this opening? What if buying an unlock let a new item appear in future awards? Try adding that kind of option. Give yourself about 12 minutes here. After buying it, check that the option becomes available, the purchase survives a restart, and the normal starting stats always stay unchanged unless you explicitly intended otherwise. Okay, now buying that unlock should let the item appear. It shouldn't give us the item's effect straight away. So, check the rule that adds it to the reward pool and force a test offer to make sure that it can show up. Then play around with it as well. Even if it's another option, it could still be much stronger than everything else that we're offering. Okay, our unlocks can affect the next run. Now we need to make sure that getting between the hub menus and game works as one sequence. In the Godot editor, we can jump straight into a scene that we're testing, such as a fight. Someone opening the exported game, the version that they can launch without the Godot editor, needs a place to begin. Our title screen can give them a start and quit. Start will just take them into the first run. Now follow what they do next. They need a pause and resume. When they die, they need to retry or visit the forge, which is our shop between runs. There they spend essence, the currency that they keep after a run ends, on a permanent up unlock or a permanent upgrade. Then they need another way to start another run. Now we can have all those screens and still be missing a button that connects all of them. So, click through the game. Can we get to the next screen? Can we leave it? All right, we will now I to create a new title screen. To do this, we're going to create a new scene and we'll actually start with the user interface or a control node. We'll rename this to title screen. We'll go ahead and save it title screen inside of our scenes folder. We'll go ahead and add a new uh script for this huh and we'll put it in the scripts folder. We'll hit create. Before we go ahead and continue on to the scripts though, we have a couple nodes we need to add and that first one is going to be a center container, a VBox container, a label, and two buttons. I'll go ahead and just duplicate that one. The last button will be called quit button. This will be start button. And the label can be title. This one we'll just call it VBox. For this one we can just call this center. And the title screen can stay this way it is. And here we'll go ahead and open up the script. And we'll add two nodes. First the title which is just a label and we'll add a time variable. We fade to black, change the scene, and then fade back in. It sounds simple, but what if changing scenes also deletes the node doing the fade? We need it to survive the swap, so we'll make the transition on auto load. It also needs to process while gameplay is paused. We'll set a busy flag while the transition runs so rapid clicks don't start another one. Then we'll handle a failed scene change as well. If the path is wrong, we need to uncover a usable screen and clear the busy state as well. Otherwise, the player is just left staring at a black screen. From here we'll go ahead and connect the start button and quit button and we'll go ahead and create those two buttons immediately. It's It's simple. We'll simply transition to uh the main scene and then from here we'll simply quit. Now, we are calling a transition this global thing which we don't have, so we'll go ahead and create that in just a second. But before we do that, we'll go ahead and also take our process and we'll add time plus delta and we'll basically add our title modulate and we're going to lerp it between uh white and orange, so it kind of gives a living glow and it's kind of shining in and out. From here, we're actually also going to go ahead and create a new script called transitions.gd. We also want to auto load this, so we're going to go ahead and go to the globals, select script, go over here and load in transitions.gd. Go ahead and open. Once we've done that, we want to extend off of the canvas layer. So, what we'll do is simply extend off canvas layer. We'll add three different variables, basically a rectangle, a tween, and a variable for true or false. From here, we're going to now see why we actually decided to choose a canvas layer. First of all, we want to make sure that the layer is above 128. This is very important because we want this transition scene to basically show up above everything. From there, we're going to create a color rectangle that's on top of everything. And in the ready function, we'll go ahead and just fade uh from zero or to zero with a duration of 0.5, so target A means the color of the alpha. The way our transition or fade will work is basically tweening the alpha of our color rectangle. This will take the rectangle and essentially make it from solid black to zero of alpha, so it basically becomes transparent. Then, we'll have the function is busy, which just returns is busy. This is so we can call this function from a outside place, basically. From there, we're going to add our change scene. This is going to basically override the current change scene. Um it's not really an override per se. We're basically rewriting it to make it nicer. So, in the first half, we're going to basically transition in. So, the way this works is we await right here a to make the alpha uh one. So, that way we basically make the color over here, the rectangle, completely black and opaque, and then we'll transition to the scene. And while the scene is kind of being loaded, then we'll wait for that to be done. So, once the scene has changed, we'll now transition back to zero over a duration right here. So, this is passed through as a variable with a default of 0.35. And that's it. Now, from there, we can also go ahead and create a reload scene function, which basically just reloads the scene. We can also create a fade out then. This basically does the first half of the change function, but it basically just does that exactly. So, it it will return if busy is true. Um we'll set busy to true, and then we'll basically pause the scene, fade in, and that's it. And then we'll call CB, whatever the callable is. From there, we want to go ahead and head over to the HUD, and we're going to replace the on retry and the on forge. The reason being because this stuff basically does what we just wrote. But instead, we're just going to call the transition. So, we're also going to find the on forge and go ahead and replace that with the exact same thing. We're just going to go to the hub. Now, inside of the hub script, we're going to replace this line right here with a start pressed uh connect. And then transition to the change scene main.scene. This will basically do exactly the same thing. So, we have the callable right here. And we'll basically connect this to well what we want. And that's it. However, one thing we need to check here to make sure that we don't have any small bugs is check to see if the transition is true. If so, we'll simply return inside of the unlock press button. From here, you can go ahead and test the button the everything we just added. Before we test this, the title screen needs finishing. Select center, set its layout mode to anchors, and the preset to full rect. So, it fills the screen and actually centers the button. Then give the label and two buttons some text. Otherwise, there's nothing to read or click. In project settings under run, make the title screen the main scene so the game always starts there. Now the paths. Our run scene is combat room inside the scene folder, not main. So, start on the title screen and start run in the hub both need that path. With a wrong path, the transition will just fade back and nothing happens. So, it's really easy to mess. We end a run and bank essence once. The guard matters because more than one call could try it to end it. Then config file saves the progress that we want to keep. In the hub, a purchase checks the ID, ownership, and cost before changing anything. The next player reads the unlock and gets its bonus once. The buttons can share a handler because each one passes its own bound ID. Now, we also fade between screens. But what if the scene path is wrong? We need to uncover the old screen and clear busy so it still works. And then from here, inside of our HUD, here we go. We can go ahead and add a new or two new new new things. First of all, we'll add a control node, duplicate that. And this one will be the pause panel. The second one will be the codex panel. Which we already have, so we can actually only have the one uh new node here, so the pause panel. Now, pausing it should stop the fight, but the controls that let us resume still need work. In this deliberately broken version, we stopped the code that listens for this controls, too. So, we can pause, but we can't get back into the game. Now, process modes are Godot's settings that decides which part of the game keeps updating while we pause. We use them to keep this menu responding while gameplay is stopped. Now, the enemy stop and resume gets us back in. The pause key is handled by the HUD, which is the on-screen layer with our health bars and other game information. That layer needs to keep listening while we're paused the game. So, pressing escape can still resume the game. But, the HUD's bar should stop moving with the fight. So, while we're paused, the HUD skips its usual update, and the pause key can keep working. Now, press escape while the upgrade screen is offering us card rewards. That screen already stopped the fight. If escape simply switches pause off, the enemies could start attacking again while we're still trying to read the cards. So, check which screen is open before resuming. Closing the pause menu and finishing an upgrade choice are different actions. Test escape in both menus. It should let us resume from the pause menu while the upgrade screen keeps the fight stopped until we choose or skip a card. But, now inside of our HUD script, we can go ahead and open this up. And at the top, we can go ahead and load the pause panel and codex panel. From there, we can also add a variable here. Codex open. Then, inside of the ready function, we can go ahead and set the pause panel to visible equal false. We can also set the codex uh visibility to false. And then, for the codex uh close, what we'll do is replace this with toggle codex. From there, we can go ahead and add to that function. I'll add it a little lower. We'll add two new functions. First, we'll add toggle pause. This will basically just toggle pause. And similarly, we'll also have toggle codex. So, for the toggle pause, we'll just return if any of these are true. For the toggle codex, same thing, but um it literally just all of the other ones. It seems like a lot, which it is. It's just we have a lot of things going on that we need to make sure we return if they're all true. From there, we'll basically just check to see if codex is open, then refresh. We'll set the paused equal to if codex is open or not. We'll play click, etc. And then the similar thing for the toggle pause. What should escape do if the codex is open? If it also opens the pause menu, we could end up with two screens trying to unpause the same game. And we'll end up with a big problem here. So, we'll decide the order. A reward or game over screen blocks the normal pause menu. If the codex is open, escape closes it. Otherwise, it toggles pause. After handling the event, we'll mark it handled so another event handler doesn't open that same press. That doesn't stop code that polls input directly. So, gameplay still needs its own pause and busy checks. Now, one thing we can do inside of the unhandled input right here is inside of this if statement where we ask it to click, we can now go ahead and toggle the codex. But of course, we don't need to do any of this other stuff because we already do that. From there, we can also just take our viewport and set input as handled and then return. Next up, what we can do is check to see if we press cancel. From there, we can go ahead and toggle the codex or pause depending on if codex is open and then we can set the viewport as handled. Now, we can go ahead and find the close codec function and we can just delete all this because we no longer need it. All right, and from here we can go ahead and close this. And what we're going to do here is I'm actually going to go over here to the game over, copy all this, and pop this into the pause panel. I'm going to hide everything else because right now it is kind of hard to see everything. Um but now inside of the pause panel, I'm going to go to the uh pause panel thing first, go to the anchor preset and select full rectangle. From here, we basically have almost everything we need. We just need to add a VBox container. And I'm going to add these two buttons in here. Duplicate one of them. And then we're going to rename them. The first one is going to be the resume button. Second one is going to be restart. And the third one is going to be the title screen, basically return to title. For everything else, we can pretty much keep the same, but I'll also just delete these two labels because we just won't need them. Unless you want one, you can have a pause button uh thing, but that's totally optional. From here, I'm going to just move this to the middle. Make it a little bigger if I can actually properly select it. And then I'll simply center it, so it kind of centers where I I created. Okay, back inside of the HUD uh script, we're going to go to the top for the ready function. And we're going to add a couple new functions or a couple new lines. So, first we're going to connect the resume button. And we're going to just go ahead and connect all the buttons that we created, basically. The title and the restart. The toggle we don't need to do anything, but for the restart and on title we do. So, let's head over to the bottom and simply add on title and on restart. They're basically super simple. We simply on restart we check to see if leaving or if busy then return. We'll set leaving to true and then we'll wait for the reload and then set it to false and then same thing for on title. And that's pretty much it. We can go ahead and test it out if you'd like. The title screen path in the HUD has the same problem. The title screen is inside of scenes folder as well. If the forge button on the game over screen still does nothing, connect it to on the forge in the HUD's ready function next to retry. Last thing, the labels. Resume and restart still both say run again and forge sits right on top of run again. So, we'll rename them and move forge down. Okay, we double click start while the screen is fading. Where should we reject the second transition? Then imagine the scene path is wrong. What needs to happen so the menu still works? Now let's follow the whole loop in a fixed game. It opens on the title screen. We double click start while the screen fades and we still only get one scene change. That's good. In the run, escape opens the pause menu and resume gets us back in. Tab opens the codex and escape closes the codex instead of opening the pause menu. While the reward cards are up, escape does nothing. When we die, run again starts a fresh run. Next time, the forge button takes us to the hub and start run begins another run. From the pause menu, we can go back to the title. And here's a test with a scene path that doesn't exist. The screen fades back in and start will should still work. The transition manager checks busy and rejects the second request. If changing scenes fails, it restores the previous pause state, fades back in and clears busy. We also can guard the button, but the shared transition needs its own check. Okay, pick one thing that you want the player to be able to adjust. Add a setting for it and save the value. Give yourself about 10 minutes to do this. Change the setting, close the game completely, and reopen it. The control and the game should still have those saved values. Okay, we can put that setting in another section of the config file we already used, but did we actually set its value before saving? And what do we load if the file doesn't exist yet? Give it a default, then test a full restart. Okay, we can move between the screens now. Let's give the player control over music and effects, then make sure that those choices stay saved. With the music playing, we still need to hear the attacks and the hits. Those sound effects and the music gets separate volume controls. Those sliders will just live in the pause menu. They need to work while we're paused, and the game needs to remember their values while we reopen it. The music is too loud, but the sword sounds are fine. We don't want one volume slider turning everything down together. So, we'll send music and effects through separate audio buses, with both going through master. The bus volume uses decibels. Zero dB means no gain change, not silence. Our slider go Our sliders go from zero to one. So, we'll convert their values to decibels and add them to the base mix levels. At zero, we'll mute explicitly. That way, setting a slider to full keeps the balance we chose instead of resetting every bus to the same level. Okay, now at this point, we want to go ahead and head over to the audio bus sounds. Now, in here, this is where we can manage all the audio sounds and add different things. The way this works is we'll add a bus twice. From here, we can add this new one as sound effects, and this other one will be for music. For the sound effects, we'll drag this down to -4 or so. Whoops. For the music, we'll drag this down to -12. Usually, you don't want music to be overpowering. And again, similarly for sound effects, you don't want that to be super overpowering to other audio things inside of your game, especially if you had like dialogue, for example. And if you go ahead and actually hit save, like control S, you will notice that we now have the default bus layout. If it doesn't, you can go ahead and save as, and of course save it as this thing. Another cool thing that will happen is inside of the project settings inside of our audio, the default bus layout will end up being this new thing that we just created. Now, if you want to add effects, then you are more than welcome to. I myself am not an expert in audio control, so I do know some of the stuff like compressor, EQ, uh limiters, reverb, things like these. Some of this might actually even make sense to you like pitch shift. This is a really cool thing. Um if you want to make your game kind of scary, things like that. Um you know, you're more than welcome to go ahead and play around with these uh sound effects, but I'm going to not add anything for this video. In the future, I might like to collab with someone who knows more on what they're doing, so that would could be cool. Uh but for now, we're just going to leave it everything as is. Okay, now inside of our script, inside of our audio manager script, we're going to go ahead and open this up, pop it out, and at the top, we're going to add a new variable or constant a bus base DB. This is basically to have what I just set, but we're going to do this all in code. Okay, let's say that we replace the hit sound. Do we want to find its file path in every enemy script? No, the gameplay can just ask for hit, and audio manager decides which stream and player to use. We can use multiple variants and pool of players for overlapping sounds. The pool is still limited. If every slot is playing, reusing one can cut off its current sound. Now, we're going to add a couple new sounds before we continue. First, we'll have pick up. This is just two little audios. We'll also have upgrade, which we did call at one point, but we just never had it. So, we'll have that as well. From there, we'll also add click, which we also called at one point, but we just didn't have it in here. Uh everything else can stay variation, etc. All that is fine. Okay, now the important part is right here. Below the audio stream player is the bus. Now, the cool part here is this is allowing us to basically play the audio in a specific bus. So, here we can play it in the bus SFX. Or set the SFX to uh or the bus to SFX, sorry. From there, just so we can have a bit more testing, is inside of the preload, right below the continue, we can push a warning. Basically telling us that we're missing some sort of file. Uh this will be very helpful for you if you guys ever misspell anything. Um it is useful for me, too, but obviously I already have everything working. Um but yeah, that's pretty much it for that. Now, what we want to do is head over to our room controller. And inside of the upgrade it chosen, right after the apply the upgrade, we will now play the new upgrade sound, which we just created. Now, press retry to start a new run. We shouldn't hear the same music restart from the beginning every time, though. That would just get like annoying. We keep the music player running when the run scene changes. Godot lets us do that with an autoload, an object that will stay loaded as we move between scenes. If the same track is already playing, we can just get it to keep playing. If we need another track, this version will just fade down, switches it, then fades back up. The two tracks don't overlap this way. So, there's a short quiet gap between them. Now, from there, we'll head back inside of our audio manager, and we're going to go ahead and add some new music, basically. So, again, we have music calm and combat. We'll have a music DB. Then, from there, at the bottom, we'll add a music stream. Um so, basically, the same thing that we had before for everything else. We'll also add duck token, music tween, and duck tween. Okay, we clear the room and play a sound, but the music makes it hard to hear. We could turn the mute sound up or briefly lower the music around it. That temporary reduction is called ducking. We'll keep the normal music gain and temporary reduction separate, then combine them for the final volume. A setter updates that volume whenever either value changes, including during a tween. If another duck starts before the first finishes, we'll update the request token, so the old timer can't restore the music too early. Then, from there, we're going to add a variable with a set function. It's going to be basically music gain. We'll have the music be equal to the value with our function update music volume. We will also create another variable, duck gain, which is the exact same thing with the update music volume. Now, the important part is the update music volume function, which we'll add at the bottom. This one will basically just set our music player's volume equal to the music gain plus the music duck or the duck gain. From here, we need to go ahead and add our music stream player inside of our ready function. So, we'll add this at the very bottom. We'll basically create a music stream player, basically the same thing that we did for this, but we're just doing it for music. And we only need this once because music should only be playing once. Once we've done that, we can for loop the music inside the music and create a or get our files and load them all in. And there, similarly to having our play function, we are going to need a play music function. For this one, we're going to return if name is equal to the current music already. If it's null, then we'll also return. If not, then we'll set our current current music to the name of the thing that we're trying to play. And then we want to fade in from one song to another. We don't want to abruptly change something. That's how things look kind of unprofessional and just don't look super polished. So, to fade this, we'll use a tween. We'll tween the property by taking our gain and going down to -60. Then we'll have a callback and basically play the next music. Now, from there we can go ahead and close this and inside of our title screen function, inside of our ready script, we can go ahead and call the play music function with play calm. We can also do this inside of our hub. Right here, we can play music calm. And then inside of our room controller in the ready function, we can play the combat. Before we test the music, there's one setting on the music files themselves. Select music calm in the file system, open the import tab, set loop mode to forward, and click re-import. Then do the same for the music combat. Without this, each track plays once and when it ends, the music will just stop. Next, let the music repeat from the end back to the beginning. That is the loop. Look at the waveform, a graph of the sound. If its end does not meet its beginning, the wave jumps at that join. And we hear a click every time the track repeats. The music files in our project were generated by a small script. So, we can and where each tone finishes. One complete up and down repetition of a sound wave is a cycle. Every tone in a our track finishes a whole number of cycles over the whole loop. No tone stops halfway through a wave, so the end meets the beginning. Now, we can do that because we generate every tone ourselves. In recorded music, we can't choose how many cycles each instrument plays, and sound can still be ringing at the join. So, listen to the loop in the game and let it repeat at least twice. If the join clicks, move the loop point or use a crossfade. Briefly overlap the end and the beginning, fading the end out as the beginning fades in. From there, we'll head back inside of our audio manager and at the very bottom, we're going to add a duck music function. From here, we'll basically add to the duck token. We'll take our token and add or make it equal to the duck token. And basically, the idea here is to just tween it. We're just going to create a timer and then tween everything, and that's pretty much it. The thing that earns this is going to be inside of our room controller inside of our room finished function. Below our room cleared, we can do this right below or right before the set status, actually. We'll have the the room cleared being played and then duck the music. We'll also head inside of our player controller. And then the on died, whoops, the on died function right here, right next to the slow mo, right below that, we'll go ahead and duck the music as well. Now, what we can do is head back inside of our audio manager and add one more function, apply mix. From here, we'll basically for loop through our bus base DB. And the point here is to scale each bus from its authored label. So, one means as mixed rather than as loud as possible. This basically helps us actually mix everything. Now, the cool part is actually saving all this inside of our meta progression. So, what we'll do is create audio settings by default and then we'll create a function at the bottom set audio settings. This will basically apply the mix, save the game, basically everything that we need. From there, we need to now go to the loading game and this is where we'll load in our audio. So, from here, we're going to go ahead and basically get four loop through our audio settings. And then we'll load in our audio. Now, of course, similarly in the save game, we need to go ahead and do the exact same thing but just save it. We'll go ahead and four loop here and then set the value rather than actually making it equal, so we're just setting it. Now, inside of our ready function, we can go ahead and apply the mix uh after we load the game. So, it's obviously very important that we load the game first before we actually apply the mix. From there, inside of our HUD, we're going to go ahead and basically add all the settings for music and audio and things that we can actually change. So, to do this, what we can do is actually inside of our pause panel right here. I'm going to actually duplicate this VBox container. Actually, sorry, I'm not going to duplicate anything just yet but inside of our pause panel uh inside of our VBox container I'm going to add a label and then an HSlider and I'm going to duplicate the slider two times and the label two times. >> I'm going to also add a VBox container and everything we just added will be inside of that VBox container. It's just so it's a bit more organized. This I'm going to rename it to audio. This will be master label. No spaces. This will be master. This will be SFX label. This will be just SFX. And then lastly, music. But this will just be music label. And the last one will just be music with a underscore M. Now the important part is to actually make sure we added the labels. So here we need to make sure this says master, this says SFX. And then this one says music. And then from there, um if you notice things are a bit too close or feel that things are a bit too close, we can just go ahead and separate things just a little bit. Maybe 12 or so is not bad. I'll do the same for the top VBox controller as well. I'll go to the theme overrides and make this 12. And there we go. Now inside of the script, inside of the HUD script, here we go. We can see a slider called music on screen. But does the code know where it is? Our lockup uses the key masters, SFX, and music. So the slider nodes need those exact names. The visible labels are separate nodes. We'll start We'll set each slider's range from zero to one, load its save value, and then conduct value changes. Doing it in that order avoids treating the initial value as new adjustment by the player. Once they Once they're connected, we'll test all three in the pause menu, including closing the menu and restarting the game. Inside of the ready function, we're going to add a for loop, which basically sets everything to the default values that they should be. Because obviously everything we had was in code, but this needs to actually set everything to whatever we had inside of our saved settings. One other thing I just noticed is this should be VBox. So, if you haven't made that change or you uh haven't done that, make sure that this says VBox and not VBox container. Okay, and that's pretty much it. You can go ahead and test it if you'd like. Set the three volume sliders to different values, close the game, and reopen it. If the audio changed during the session, but the sliders reset afterwards, which part of the same saved game would you check first? The slider changes the volume, but after restarting the game, it goes back. How come? Well, look at where we save. We're writing the save before we've put the audio values into the config. Set values only change the config in memory, so those later settings won't be in the save files. Put the audio loop above save, so all the values are there first. Then set music to something easy to recognize, like 0.3, close the game, and reopen it. Check the slider and listen to the music. Changing it during one session should test the volume control. Restarting tests whether it we saved it. Okay, is there an action that's still easy to miss while playing? Try adding a sound for it. It could be selecting a card, collecting something, or a door changing states. Give yourself about 8 minutes to just try everything. Compare it on and off during gameplay and check it against its existing mix. The new sound should make that action easier to recognize without drowning out another. Check repeated use and relevant volume sliders as well. If it becomes distracting when played often, try a quieter another variant or fewer triggers. The comparison in context matters more than how the sample sounds by itself. Once the settings survive a restart, there's one route to finish. What happens after we beat the final boss? We can lose a run and start again. But, what happens if we win? A floor is a set of connected rooms. Before this change, beating a floor's boss just created another floor. We can keep going until we die, but there is no victory screen. For this game, floor three is will be the last floor. After that boss, we still let the player choose or skip the reward. Who then show victory instead of creating another floor. That order matters. We shouldn't end the game while they're still reading the cards. The victory screen shows the same run results and buttons that we would get after a death. We save the results once, then let the player retry or visit the forge, which is the in-between shop. Now, test both endings. Losing and winning should each give us a way to start again. Okay, we are almost done. The final thing we need to do is give the game a ending. At this point, we basically can descend infinitely. Now, if you want to keep it that way, you're more than welcome. But, uh inside of the room controller, we are going to create a final floor. And usually it's three floors, so that's what we'll do. Inside of our upgrade chosen, this is where we're going to ask if we are on the final floor. We will do this inside of the reward question here. So, it will ask if the floor depth is inside the final floor. If so, what we'll do is instead of entering the next floor, we will basically show victory. If we are not on the final floor, then we'll just enter the next floor. Closing this, we'll head over to the HUD, and inside of our game over, right next to the summary, we'll duplicate this and rename this to heading. We can move this above the summary if we want, but that's pretty much it. Um we can actually or we should probably move this text. Uh and that's pretty much it. From there, we'll go back inside of our HUD, and we are going to create a new function show victory. This will basically check to see if game over is true. Uh if it does is, then we'll return. Otherwise, we'll show game over equal true. And then, we will set the heading text to the forge is free. This basically means like we're free. Um some sort of text to tell us that the game has been finished. Now, inside of our show game over function right here, under the essence being created, we can now set this text you died. Then, at the very bottom, we can also set our pause panel visibility to false. And everything else is unchanged. And that's it. We are pretty much done with the game. You can now go ahead and test the game, play it a couple times. For one last final check, change the final floor in a test copy. Now, what should happen after a boss reward on an earlier floor? What should happen on the final one? Then test victory, retry, and your saved unlocks. Take a few minutes to follow that whole sequence. Earlier boss rewards should take us downstairs. The final one should show victory and bank one once. Retry should reset the temporary run data and keep permanent progress. Restore your intended final floor value afterward and then run through it again with that setting. Separately, exporting packages the project into something that we can launch outside of Godot. We'll test that version through the menus and complete runs as well. Now, let's make the version someone else can play. Basically, a file that someone else can click and play our game. Now, Godot builds it from export templates. So, first open the editor menu, choose manage export templates, and download the templates for our Godot version. It's a pretty big download, so it can take a while. Then open project, export, click add, and choose Windows desktop. If you're on another system, pick that one instead. Click export project. Pick a folder outside our project, like a build folder, and name that file. At the bottom, untick export with debug, so we get the release version that we'd have in the player. And then save. Godot writes the program in a dot package file with our game's data next to it. So, keep those two together. Now, double-click the program. Our title screen should come up, and nothing here needs the editor. One more thing for testing. Our save file isn't in that folder. Open project, and then open user data folder, and that's where it lives. To test a first launch with no progress, move that save file out of the folder for the test, then put it back afterwards. Launch the exported file fresh. Press start and play. Pause and resume. Choose an upgrade, die, spend essence, which is the current uh currency kept after a run at the forge, and start again. Then check the winning route as well. Use a fresh save with no progress yet, and existing save for a returning player. Change a setting, finish the run, and reopen the game. Okay, a file left out of the export or a file path with the wrong capital letters can cause trouble even if the game worked in development setup. This was something I mentioned a couple times, but it is very important now that we're exporting the game. Testing the pause menu by itself won't show whether retry leaves the next run paused. We need to try those actions together. We won't catch every bug this way, but we'll find problems in the steps someone needs to just play the game. Now, we have the routes around the game as well as fights, escape checks, which screen is open before changing pause, a transition rejects another request while it's busy, the audio slider change separate buses, and we add to their settings in the config before saving. Then we reopen the game to check that they stayed. Finally, a boss reward either takes us downstairs or ends the run in victory. Both winning and losing need to bank once and let us start fresh. Okay, I want you to pick one small thing that you still want to change. Before you edit it, what should happen when it works? Write that down so you have something to compare it against after making it. Then try that change in the exported game and follow the route around it, including leaving the screen and restarting it that should affect it. Your change could be visual and input improvement or a clear description or small feature. The useful part here is being able to explain what you changed and show that it works in the build someone else would play. Then check that the surrounding flow still works. If you want to keep extending the game, use the same approach. Choose one change, work out what it depends on and test it before adding the next one. Okay, and that's the game. We started with a knight that could only walk around and now we can dash through attacks and land hits that feel like hits. There are five monsters and a boss that each make us move differently. Rooms that build around themselves into floors and upgrade cards that can make us stronger where corruption makes the fight harder. We have gold, shops and items and a death screen that shows how the run went. Essence we keep between runs and the forge to spend it in. And around all that, there's a title screen, a pause menu, sound settings that we can stay saved, a way to win on floor three, and a file that we can hand to someone else to play. That is a finished game and now it's yours to change. Thanks for building it with me. I hope you guys enjoyed this course. If you guys want more guided courses, go check out codingquest.io.

Generated algorithmically for Search Engine Indexing.

Summarize Another Video