mercredi 28 janvier 2015

Do the same interval just laggier in javascript

I'm making a html canvas game and I use requestAnimationFrame.

My problem is that in fast computers it runs at full speed (60 fps) But in slower computers it runs slower like 10 fps, and then the game slowes down.

I want to do it at the same speed just do it laggier.

Like in minecraft, w.o.t. or l.o.l., the zombie comes to you at the same speed, just laggier if you use worse computer.


Sorry for my English and Thanks for the answers!


This is my code:





var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
var x = W / 2;
var y = H / 2 + H / 4;
var line = [];
var enemyX = [];
var enemyY = [];
var counter = 0;
var enemyW = H / 16;
var left = false;
var right = false;
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
loop();

function loop() {
counter++;
if (counter == 10) {
counter = 0;
}
requestAnimFrame(loop);
ctx.clearRect(0, 0, W, H);
if (left) {
x -= H / 256;
} else if (right) {
x += H / 256;
}
line.unshift(x);
line.splice(100, 1);
for (var i = 0; i < line.length; i++) {
ctx.fillStyle = "rgb(150,255,150)";
ctx.beginPath();
ctx.arc(line[i], y - (i * H / 128), H / 64, 0, 2 * Math.PI);
ctx.fill();
}
if (counter == 0) {
var rn = Math.floor(Math.random() * W);
enemyX.unshift(rn);
enemyY.unshift(H);
}
for (var i = 0; i < enemyX.length; i++) {
ctx.fillStyle = "rgb(205,100,100)";
ctx.beginPath();
enemyY[i] -= H / 128;
ctx.fillRect(enemyX[i], enemyY[i], enemyW, enemyW);
ctx.fill();
}
ctx.fillStyle = "rgb(100,205,100)";
ctx.beginPath();
ctx.arc(x, y, H / 64, 0, 2 * Math.PI);
ctx.fill();
}
document.addEventListener("keydown", function(e) {
if (e.which == 37) {
left = true;
} else if (e.which == 39) {
right = true;
}
});
document.addEventListener("keyup", function(e) {
if (e.which == 37) {
left = false;
} else if (e.which == 39) {
right = false;
}
});



* {
margin: 0px;
}



<canvas id="canvas">Browser doesn't support HTML5 canvas</canvas>


Aucun commentaire:

Enregistrer un commentaire