The codeleap for this section may be accessed here. In this section, we will discuss a few different ways you can animate a sprite. Following this explanation, we will implement a few of the methods.
Subsections
01 A Word on 'enterframe'
02 Animating a Sprite Using its Attributes
03 Animating a Sprite Using Frames
For our purposes, animation depends on variables changing. By this I mean that for a sprite to move across the screen from left to right, its attribute x must keep increasing.
To implement this effect, we will be using the class’s onenterframe
function. Code within this function will be executed on every turn or “frame”. In the context of animation we can use this to move a sprite across the screen, have it fade in and out, or even cycle through different frames on the sprite sheet for some traditional animation.
Now that we understand the ‘enterframe’ function a little more, let’s actually try using it to animate a sprite. We’ll implement it in our example code. (Once again, you can access it from here.) Confirm the attribute animation works by clicking RUN and observing the sprite changing. The sprite should move from left to right, spin, and fade away as it reaches the other side of the screen.
bear
class, which has already been initialized.onenterframe
function under 03.2 Sprite Animation Attributes, add:
this.x += 4;
this.opacity -= .01;
this.rotate(15);
if(this.x > stgWidth){
this.scene.removeChild(this);
}
As mentioned before a sprite sheet is an image containing many sprites. Sprites are spaced evenly across the sheet in order to create a consistent animation. This is especially important for something like a walk cycle, which loops through several frames in order to create the illusion that a sprite is walking. An example of a walk cycle is demonstrated below in Figure 3.01.
chara1.png
.onenterframe
function. The second involves setting the frame cycle in the initialize
function.
if(this.frame >= 7){
this.frame = 5;
}
else{
this.frame++;
}
onenterframe
function should only contain the code to move the sprite across the screen and the code that removes it once it's reached the end of the stage.initialize
function, under 03.3 Alternative Frame Animation add:
this.frame = [5, 6, 7];
null
the last element in the array.