var characterName; var score;
Variables can be given almost any name except for a few rules:
- Names cannot start with a number, but they can be added anywhere else in the name!
- They are also case-sensitive, meaning “weapon” and “Weapon” are two different variables.
Another thing to note is you only need to declare a variables once.
var characterName = "Rich"; // Declare the variable characterName with the name Rich characterName = "Steve"; // Lets not go with Rich but lets change it to Steve!
Notice when I wanted to change the name I put in the variable characterName I did not put the keyword var in front of it.
There are six primitive datatypes:
Numbers are essential in game development. They are used to keep track of score, how far an enemy is from the player, and how many lives the player has left, etc…
To simply create a variable with a number you would declare it like the example below:
var score = 100; // A number without decimals var playerLocation = 20.10; // A number with decimals
Strings can be considered as a sequence of characters. These can be used to display helpful information on the HUD or dialogue within the game. Take the score for example.
It would be helpful if there was text in front of the score number within a game to make it clear where the score number is located on the HUD.
var scoreString = "Score:";
The Boolean primitive can only have the values true or false besides for an exception. This is very useful when trying to detect if a player has been it by a projectile or another NPC.
Booleans declaration examples:
var isPlayerHit = false; var playerHasAmmo = true;
There are some rules to the Boolean that should be kept in mind:
- False Is when the variable is 0, empty, undefined, NaN, null, or undefined.
- If it’s not on the list above, then everything else is considered true.
Here are a few more examples of how booleans would work:
var ammo = 0; // false var scoreString = “Score:”; // true var ammoCount = 123; // true var playerName = “”; // false
It’s very important to understand these rules, because it could cause some unexpected results when testing, and sometimes they will be hard to find and fix!