I am creating a HTML game where you fight monsters and stuff and this is part of the game loop for dealing damage:
var hp = 1000000000;
var speed = 10;
var power = 5;
var lastCalledTime;
var fps;
var GameLoop = function() {
if(!lastCalledTime) {
lastCalledTime = new Date().getTime();
fps = 0;
return;
}
delta = (new Date().getTime() - lastCalledTime)/1000;
lastCalledTime = new Date().getTime();
fps = 1/delta;
hp = hp - (5 * speed * 0.1) / fps;
};
var animFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
null ;
if ( animFrame !== null ) {
var recursiveAnim = function() {
GameLoop();
animFrame( recursiveAnim );
};
animFrame( recursiveAnim );
} else {
setInterval( GameLoop, 33.33 );
}
http://jsfiddle.net/u0k7tbv4/2/
Power is how much you deal with each attack and each level of speed gives 0.1 attack / second. With 5 Power and 10 Speed it should deal 5 damage every second and that seems to be the case in the fiddle.
But I'm not sure, I only used requestAnimationFrame
because I heard setInterval
is unstable and so it would be nice if someone could validate the code.