I've been using javascript's setInterval function, and to combat the inconsistencies of the times my function is called I've been using a delta value. This is my first time using a delta value,
so I probably missed something, any help would be appreciated.
The script:
Code: Select all
var canvas = document.getElementById("testCanvas");
var g = canvas.getContext("2d");
setInterval(update, (1000/60));
var x = 50;
var xvel = 2;
var lastTime = new Date();
var oneFrame = (1000/60); //we want 60 fps, so divide one second by 60
var extra = "";
function update() {
var currTime = new Date();
var delta = currTime.getMilliseconds()-lastTime.getMilliseconds();
var incrementAmount = ((xvel/oneFrame)*Math.abs(delta));
x += incrementAmount;
if(x > canvas.width-25) {
xvel = -xvel;
x = canvas.width-25;
} else if(x < 0) {
xvel = -xvel;
x = 0;
}
paint();
lastTime = new Date();
}
function paint() {
g.clearRect(0, 0, canvas.width, canvas.height);
g.strokeStyle = "#000000";
g.strokeRect(0, 0, canvas.width, canvas.height);
//actually draw our square
g.fillStyle = "#0000FF";
g.fillRect(x, 25.5, 25, 25);
g.fillText("x: "+x+", extra: "+extra, 5, canvas.height-25);
}