Take a look at the movement function of my game:
https://jsfiddle.net/qk7ayx7n/92/
var canvas = document.getElementById("canvas");
var ctx=canvas.getContext("2d");
height = window.innerHeight;
canvas.width = window.innerWidth;
canvas.height = height;
playerY = height / 2;
playerX = 50;
var circle = new Image();
circle.src = "https://s21.postimg.org/4zigxdh7r/circ.png";
ctx.drawImage(circle, playerX, playerY);
move();
function move(){
velocity = height * 0.00050; // the velocity should be proptional to screen height.
startPos = playerY,
endPos = 0,
distanceY = endPos - playerY,
startTime = Date.now(),
duration = Math.abs(distanceY) / velocity;
requestAnimationFrame(startMoving);
function startMoving(){
var elapsedTime = Math.min(Date.now() - startTime, duration),
cbEnd = false;
if (elapsedTime < duration){ //time's up
setTimeout(function() {
requestAnimationFrame(startMoving);
}, 1000 / 60);
}
else cbEnd = true;
playerY = startPos - (elapsedTime * velocity);
console.log(playerY);
ctx.clearRect(0, 0, window.innerWidth, height);
ctx.drawImage(circle, playerX, playerY); //drawing circle
if(cbEnd) console.log("over");
}
}
Now, I will explain: My actual game is a game where the velocity of the player changes as the game progresses. The speed is proportional to the window's height, because the player's goal is to move up. I'm using this technique in order to better control how many player-draws I perform. We will get to the problem with that later.
I'm also using this technique(see the answer)to measure the timings in case there was a lag in the last frame, it will just cover the distance it was supposed to cover, it also means that the target Y will always be reached on time on all devices.
The FPS average is the biggest issue I am running into. Different devices have different specs. in order to create a good game for all devices I must master this function:
setTimeout(function() {
var fps = 60;
requestAnimationFrame(startMoving);
}, 1000 / fps);
I have tested my game on many devices, on some the fps needs to be 40, 50, 30 or something else in order for the game to run smoothly(which means each player "move" will be equal to it's previous, otherwise they will experience lag). So I was thinking, either secretly running the game as the game "loads" for the first time and finding out the average FPS, or maintaining some kind of a learning curve in order to adjust how many times this function runs. Either way I do not really know how to achieve it perfectly, I know it may be hard but please I need some help with this.