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.
cat.vx = 0;
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:
function setup() {
//Create the `cat` sprite
cat = new Sprite(resources["images/cat.png"].texture);
cat.y = 96;
cat.vx = 0;
cat.vy = 0;
app.stage.addChild(cat);
//Start the game loop
app.ticker.add(delta => gameLoop(delta));
}
function gameLoop(delta){
//Update the cat's velocity
cat.vx = 1;
cat.vy = 1;
//Apply the velocity values to the cat's
//position to make it move
cat.x += cat.vx;
cat.y += cat.vy;
}
When you run this code, the cat will move down and to the right at one pixel per frame:
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.