Tutorial: How to make a top-down shooter in JavaScript

Lesson 4) Getting started with objects

Is it wrong to objectify people?

Right now, our player's x and y coordinates are stored in two separate variables; player1x and player1y. It would be much better, however, if we could put all the variables relating to the player into a single container. This is possible in JavaScript, and such containers are called "objects."

Think of an object as a variable which, instead of holding a single value, contains a number variables and functions. Variables contained inside an object are called "properties," while functions contained inside an object are called "methods." You should know this - you used the "rect" method of the "c" object to draw the player in the last lesson.

Putting things in objects keeps them logically ordered, and saves you time/processing power. Imagine you have 100 bad guys on the screen. You'd need to create so many variables - badGuy1x, badGuy1y, badGuy2x, badGuy2y.... badGuy100x, badGuy100y. And that's just coordinates! You'd also need health, type, weapons, ammo, speed, etc.

But if we had a bad guy object, which had all these properties built in, we could just copy this object whenever we needed to put a new baddie on the screen.

So let's make our player character into an object, and put the x and y properties inside it. replace the "var player1x" and "var player1y" lines with:
function Player () {
this.x = 395;
this.y = 295;
this.w = 10;
this.h = 10;
}
var Player1 = new Player();
The "this" bit indicates we're using a function to create an object, by defining its properities. When we use a function to define an object like this, the function is called a "constructor."

In the "var" line underneath, we "construct" a new variable called "Player1" which will be a "new" Player() object. In doing so, Player1 inherits all the values that the main Player constructor has.

If we want to refer to these properties in our program, we just use Player1.x, Player1.y and so on (note that I've added height and width properties to our player also). So we need to update our rect line to reflect this:
c.rect(Player1.x, Player1.y, Player1.w, Player1.h);
This update hasn't affected our game in any way, but it has streamlined our code for things to come. Next, we'll allow the user to move the player around the screen.

Go to lesson 5 - Detecting key-press input