Using velocity properties

To give you more flexibility, it’s a good idea to control a sprite’s movement speed using two velocity properties: vx and vy. vx is used to set the sprite’s speed and direction on the x axis (horizontally). vy is used to set the sprite’s speed and direction on the y axis (vertically). Instead of changing a sprite’s x and y values directly, first update the velocity variables, and then assign those velocity values to the sprite. This is an extra bit of modularity that you’ll need for interactive game animation.

The first step is to create vx and vy properties on your sprite, and give them an initial value.

  1. cat.vx = 0;
  2. cat.vy = 0;

Setting vx and vy to 0 means that the sprite isn’t moving.

Next, in the game loop, update vx and vy with the velocity at which you want the sprite to move. Then assign those values to the sprite’s x and y properties. Here’s how you could use this technique to make the cat sprite move down and to right at one pixel each frame:

  1. function setup() {
  2. //Create the `cat` sprite
  3. cat = new Sprite(resources["images/cat.png"].texture);
  4. cat.y = 96;
  5. cat.vx = 0;
  6. cat.vy = 0;
  7. app.stage.addChild(cat);
  8. //Start the game loop
  9. app.ticker.add(delta => gameLoop(delta));
  10. }
  11. function gameLoop(delta){
  12. //Update the cat's velocity
  13. cat.vx = 1;
  14. cat.vy = 1;
  15. //Apply the velocity values to the cat's
  16. //position to make it move
  17. cat.x += cat.vx;
  18. cat.y += cat.vy;
  19. }

When you run this code, the cat will move down and to the right at one pixel per frame:

Moving sprites

What if you want to make the cat move in a different direction? To make the cat move to the left, give it a vx value of -1. To make it move up, give the cat a vy value of -1. To make the cat move faster, give it larger vx and vy values, like 3, 5, -2, or -4.

You’ll see ahead how modularizing a sprite’s velocity with vx and vy velocity properties helps with keyboard and mouse pointer control systems for games, as well as making it easier to implement physics.