I am working on a simple animation of a sprite in a little Javascript game, a mosquito that is changing state while flying towards right. These states correspond to two different images in my tile sheet.
So far I have been doing this, but the animation is very irregular:
for (var i = 0; i < mosquitos.length; i++) {
var mosquito = mosquitos[i];
setInterval (updateAnimation, 500);
mosquito.update();
// rest of code non-relevant to animation here...
and then, later:
function updateAnimation () {
next();
function next () {
mosquito.state = mosquito.FLYINGRIGHT1;
setTimeout (previous, 500);
function previous () {
mosquito.state = mosquito.FLYINGRIGHT;
}
}
}
The two states are of course FLYINGRIGHT and FLYINGRIGHT1... problem is that mosquito starts animating very quickly and very irregularly. I would like it to change state, ie every half of a second. I tried with different time periods but it is always the same effect.
I can produce a jsfiddle of the whole thing, if what I am missing is not so obvious.
Thank you for any help and insights.
Here's the game in question, from my website:
http://www.retroinvaders.net/laurasworld/src/laurasTriviaLevels.html
I think you should rethink this part:
var mosquito = mosquitos[i];
setInterval (updateAnimation, 500);
I suppose you want every new 'updateAnimation' get a different mosquito (mosquitos[0], mosquitos[1] .. mosquitos[i]). But what really happens is something different. Every time you get the same mosquito (mosquitos[i]). This is because of asynchronous behaviour of setInterval() function.
function updateAnimation () {
next();
function next() {
// every time, mosquito is equal to mosquitos[i]
// and NOT mosquitos[0], then mosquitos[1] ...
mosquito.state = mosquito.FLYINGRIGHT1;
setTimeout (previous, 500);
function previous()
{
mosquito.state = mosquito.FLYINGRIGHT;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.