Вопрос

I'm creating a diamond like game (hit 3 tiles same color to score) and i'm having an issue with animation productivity. What i do now, is making one interval that initiate 'falling' for each tile (more intervals) which are cleared when theres another tile underneath it.

For example:

function fall(elem){
     intervals[intervals.length] = setInterval(function(){
        var offset=$('#game_window').offset();
        var a = parseInt(elem.style.left)+offset.left;
        var b = parseInt(elem.style.top)+offset.top+size+1;

        var bottom = document.elementFromPoint(a,b);



        if(!bottom){    
            elem.style.top=parseInt(elem.style.top)+40+'px';
        }else if(bottom.className.indexOf('tile')>-1 ||    parseInt(elem.style.top)>=300 || game_paused==true){
            clearInterval(intervals[intervals.length-1]);
        }
    },50);

}

setInterval(function(){
$('.tile').each(function(){fall(this);});

},50);

But ofcourse its not efficient at all (well, at least it doesnt work in real life well). I have read that maybe setTimeout would be better, but i rejected this option because the script would have to wait to exegute each function one by one.

I also consider using css3 transition , but i dont know how to simulate collision there. Hope you can help me get on proper path, yet i know that its probably not good way of making any type of game.

EDIT

I ended up with getting rid of additional intervals, so for example:

function fall(elem){
            var offset=$('#game_window').offset();
            var a = parseInt(elem.style.left)+offset.left;
        var b = parseInt(elem.style.top)+offset.top+size+1;

        var bottom = document.elementFromPoint(a,b);

        if(!bottom){
            //something
             }else{
            //something
             }

}

setInterval(function(){
$('.tile').each(function(){fall(this);});  
},50);

And i guess the game works a bit better.Its still laggy, but i think its fault of too much unnecessary parts of my program. Thanks

Это было полезно?

Решение

You probably do need to make one drawing loop (with setTimeout/setInterval or with requestAnimationFrame - I recommend the latter) and compute all your "next frame logic" there. You need to loop through all objects that need to be animated and draw their next frame depending on the current state of the game.

If I understand you correctly, you don't want your diamonds to move one after another. This is usually achieved by drawing the next frame on an invisible canvas and then swapping it with the one currently being displayed and so on. If you are using DOM then I imagine that your buffer will be a hidden <div> tag. Also note that if your game will start animating quickly the effect of "not simultaneous animation" might not be even visible

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top