Introduction
In my previous blog, I told you how we can use sprite sheets in Mini Micro. Today, we are going to learn how to play an animation on a sprite in Mini Micro.
This is the 5th part of this series. Here are links to previous ones:
- How to render a sprite
- How to register a click on sprite
- How to use Bounds on Sprites
- How to use SpriteSheets for Sprites
Most blogs in this series were very short, so this may probably be the last part of the series.
Animation
Have you ever heard of a flipbook? It is some papers bound together, which, when flipped, reassemble an animation. Basically, multiple images played at a speed is animation.
As in the 4th Part of this series, we learnt how we can extract a SpritSheet and store multiple images into 1 array. In this part, we are going to use the same array like a flipbook and will try to flip the pages(images stored in the array) onto the sprite.
For this, we need simple maths.
[frame1,frame2,frame3,frame4,frame5]
Let's say when we flip the pages of a flipbook, we flip them like
- Page1
- Page2
- Page3
- Page4
- Page5
Similarly, to show an animation like a flipbook on a sprite, we need to change its image periodically.
If you do remember, in Mini Micro sprite map has a key-value pair of images. Which can be changed by giving an argument to sprite_name.image
.
Now we need to change sprite_name.image
periodically.
This can be done using a while loop.
Let's say our images are stored in an array known as frames
, then we can do something similar to the snippet below to change sp.image
to an indexed value in the array.
sp.image = frames[]
Now this indexed value must go up periodically, where we need some basic math.
In Mini Micro, we have a keyword time
which returns the number of seconds since the script started to run. This can be multiplied by the chosen animation_speed
rate by us.
But the issue currently is that when time*animation_speed
goes above the length of the frames array, we get an error.
For example, in this demo script
frames = ["x","y","t","v"]
while true
print frames[time*10]
end while
I get an error of this.
Runtime Error: Index Error (list index 4.02457 out of range) [line 4]
This error can be resolved if we use the %
operator in our equation with the length of the array.
This would give us this equation:
sp.image = frames[time * animSpeed % frames.len]
And that's how we play animation in mini micro.
Given below is a link to the official wiki, which has a demo code that can be used to test.
That's all for today. Till then, stay awesome and bye!
Top comments (0)