Saturday 14 September 2013

Variables: Health, Timer and other uses

Variables are parameters you create that can represent various attributes such as time, health, number of users and basically anything you want. You can find the variable creation menu on the Data section of Scratch and to create one all you need is to click the button "Make a Variable". In the example below we created the variable "Health" to represent the total life our character will have in the game. All the commands related to variables are present in the menu as well.

Creating Variables
Note: when creating this variable we set it for all sprites so we can specify how will the enemy will interact with the character and set how much life he will lose or gain.

Then we create a sprite with various costumes to represent our health bar. Notice on the left that each costume shows a small decrease in the amount of green and the same increase in red, representing life loss or gain.

Drawing the health bar


Next we need to write the script of how will the health variable will work.

Changing health bar costumes

Now deciphering the code; when the game starts we want the health to be set to 100, so the costume will be the full health costume. If the character is damaged by an enemy we need to change the costume according to how much health the character will have after being damaged and, since we made 10 different costumes for the health bar, we divided the current health of the character in multiples of 10, setting the costumes accordingly. This creates the effect that the health is decreasing as the character suffers damage.

But in order to damage our hero we need to create enemies and program them to do so. We chose two sprites that have 2 or more costumes to create an element of randomness as to when will the enemy attack, i.e. only one of the costumes will damage the character when in touch with it, the other will be the moment our here can escape.The first line of code tells the sprite to point towards our hero, basically just so the enemy can deal a frontal attack, instead of attacking with their backs turned to the character. The next line tells the sprite to change their costume after a random time, in our case, 1 or 2 seconds, but you may set it as you see fit. In the last line we set that when the the sprite is in the second costume and touching the character it will decrease the variable health by 10, meaning it caused damage to the hero. 

Changing enemy costume

And finally we need to give our hero a chance to survive, so we create a pickup that will restore health when touching the character. But we don't want it to restore health forever, so we add the "Hide, Wait 3 Seconds and Show" commands so the pickup will disappear for a few seconds before being reset. The "Set Size" command simply diminishes the size of the pickup to fit the screen in a better way.

Reducing health


Below is the game:

No comments :

Post a Comment