I am making a little game similar to tetris. I need the blocks to fall faster as the players score goes up I currently have this code:
setInterval(function(){
if(gameOn == 1){
gravity();
}
},1000);
This calls my gravity function and which makes the blocks drop down and does all the collision detection etc.
var time = 1000 - score;
setInterval(function(){
if(gameOn == 1){
hideStuff('hover');
gravity();
time = 1000 - score;
}
},time);
I thought something like this might work, but it doesn't seem to. Any ideas? Thanks
I am making a little game similar to tetris. I need the blocks to fall faster as the players score goes up I currently have this code:
setInterval(function(){
if(gameOn == 1){
gravity();
}
},1000);
This calls my gravity function and which makes the blocks drop down and does all the collision detection etc.
var time = 1000 - score;
setInterval(function(){
if(gameOn == 1){
hideStuff('hover');
gravity();
time = 1000 - score;
}
},time);
I thought something like this might work, but it doesn't seem to. Any ideas? Thanks
Share Improve this question asked Oct 31, 2012 at 15:22 Stewart WebbStewart Webb 1891 gold badge2 silver badges15 bronze badges6 Answers
Reset to default 3You could do a setTimeout
loop. That way, every call to setTimeout
will reflect any changes done to the value of time
var time = 1000;
(function foo(){
if(gameOn == 1){
hideStuff('hover');
gravity();
time = 1000 - score;
}
setTimeout(foo,time);
}());
You'll need to clear the interval and re-start it whenever you want to change the delay:
window.icount = setInterval(function(){
if(gameOn == 1){
gravity();
}
},1000);
var time = 1000 - score;
clearInterval(window.icount);
window.icount = setInterval(function(){
if(gameOn == 1){
hideStuff('hover');
gravity();
time = 1000 - score;
}
},time);
You need to use setTimeout not setInterval as follows :
setTimeout (function play () {
if (gameOn == 1){
hideStuff('hover');
gravity();
time = 1000 - score;
setTimeout (play, 1000 - score);
}
}, 1000);
This is an answer if the first code actually works (but doesn't get faster), you haven't really told us what is happening.
With your system you can't have a score equal or over 1000 without breaking things as the timer is set to zero or lower. I'd just decrease the times slowly each 'tick' and have a minimum value (say 100).
You can use a timeout instead of an interval and set at new timeout at the end of the callback with the desired time. That way you don't need to clear the interval every time you want to change the time.
Something like this:
// Some initial time to use
var time = 1000;
// Set the first timeout
setTimeout(callback, time);
function callback(){
if(gameOn == 1){
hideStuff('hover');
gravity();
time = 1000 - score;
// Set a new timeout with your new time
setTimeout(callback, time);
}
}
You'll have to clear the existing timer object and create a new one with the modified time.