How to Add Methods to Classes in Your HTML5 Game
Properties describe the characteristics of an object in your HTML 5 game, and methods describe the behavior. A method is a function associated with an object. You build methods very much like creating a property, but rather than adding a simple value, you assign an entire function to a name.
For example, the next version of the critter has a changeSpeed() method. When the user presses the up arrow, the critter will speed up, and when the user presses the down arrow, the critter will slow down (and eventually go the other direction). Here's the code for the critter with its new method in place:
Note that it moves when the user presses the keys. For this and most examples, a static image will not be enough to help you see what's going on.
In this new version of the program, the Critter object has a new behavior identified. Essentially, a method is nothing more than a function defined inside a class. Don't panic. It's really not that difficult to figure out. You're telling the system what to do if the user ever asks the Critter object to change speed.
Create a new property called checkKeys.
Build a new method to contain the behavior.
changeSpeed isn't an ordinary property, but a method, so you'll attach a function to it. (For the Computer Science majors out there, building an anonymous function on the fly like this is an example of a lambda function. Watch for it on the midterm exam!)
Check for keyboard input.
When you make a Critter object, it will already know how to look for its own key presses.
Change the speed based on keyboard input.
If the user presses right, increase the speed (at the default direction, positive speeds move the sprite to the right). If the user presses left, decrease the speed.
Use the setSpeed() method to change the actual speed.
The Sprite object that provides the blueprint for critter already has a setSpeed() method. Use this method to make the object move at the indicated speed.
Inside a method, use the this keyword.
When you create a method inside a constructor, the computer can get a bit confused about the names of things. For the most part, you're adding stuff to a temporary critter called tCritter. To eliminate confusion, if you need to refer to other properties or methods of the object you're modifying, use the general keyword this rather than the actual name of the object.
Modify the update() function so the critter checks the keyboard.
Remember, the main update() function happens once per frame. Anything you want to happen once per frame should be called in update(). Add a call to critter.checkKeys(). This will remind the critter to check the keyboard every frame and change its speed as needed.