Movement is slower when the canvas is larger

Using this code:

x = x + (canvas.height/250);

which occurs every 1 millisecond, add the quantity x in proportion to the size of the canvas. x is then drawn like this, so x must move down the canvas at the same speed for different screen sizes (the canvas size varies depending on the screen size). However, x moves at different speeds on my ipod and my computer.

If you want to know the full source code and html file, html is here , and the javascript file associated with it is here .

+4
source share
4 answers

, 1 . window.setInterval, , 50 , .

window.setInterval(function(){
/// call your function here e.g. add1toxfunction();
}, 50);
0

-, , :

x += canvas.height / 250;

canvas.height / 250. canvas.height. , :

distance = speed * time

distance speed, :

time = distance / speed = canvas.height / (canvas.height / 250) = 250 ms

, 2,5 . , .

, , canvas.height.

+2

.
, , , , , , .

, .
, :

pos = pos + speed * (time step) 

:

var x = 0;

var speed = canvas.width / 1000 ; // speed in pixels per milliseconds.

var lastTime = 0;

requestAnimationFrame(launchAnimate);     

function animate() {
         requestAnimationFrame(animate);
         var now = Date.now();
         var dt = now - lastTime ;
         lastTime = now ;
         // draw everything
         draw();
         // update everything with this frame time step.
         update(dt);
}

function launchAnimate() {
    lastTime = Date.now() ;
    requestAnimationFrame(animate);
}

: , , 60 16,666 .
RequestAnimationFrame, : " , , ".
, , .

, :

  • , , .
  • , .
  • ( moveTrees) . ,: -)
  • (dt) , (, , , ).

    update (dt) {        x = x + * dt;        moveTrees (DT); }

    draw() {      drawTrees();      drawHangGlider();      drawTrees(); }

, , , .

2: RequestAnimationFrame :

http://caniuse.com/requestanimationframe

(Chrome Android ).

Rq:

 // to use rAF, call this function before your game launches
 polyFillRAFNow();


// insert the function in your code.
function polyFillRAFNow() {
    // requestAnimationFrame polyfill
    var w = window;
    var foundRequestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame || w.oRequestAnimationFrame || function (cb) { setTimeout(cb, 1000 / 60); };
    window.requestAnimationFrame = foundRequestAnimationFrame;
}

Rq2: , http://gamealchemist.wordpress.com/2013/03/16/thoughts-on-the-javascript-game-loop/

+2

Thus, basically you want a relative absolute speed depending on the size of the screen, which then will be displayed on different displays equally. For this you must use interest, for example:

var pixels_in_1_percent = canvas.height/100;
x += pixels_in_1_percent

This will increase the speed to the 1%height of the canvas, if you want to increase the speed, you need to multiply it

x += pixels_in_1_percent * <number_of_percent_to_increase>

Hope this helps.

+1
source

All Articles