简体   繁体   中英

Trig problem, choppy movement of a triangle around a circle

The code below is supposed to rotate a triangle around an "invisible" circle. It is working just as I intended, however, the triangle seems to stutter around this "circle" sometimes. The CPU and memory load of this thing seem to be OK, so I wonder if it is an issue with the rounding and drawing... Help appreciated.
PS I am using SetInterval to establish a framerate. A framerate of >30 is required for what I am trying to do. Thanks.

var canvas = document.getElementById("game_area");
var context = canvas.getContext("2d");

var angle = 0;

var SinA = Math.sin(Math.PI);
var CosA = Math.cos(Math.PI);

var SinB = Math.sin(Math.PI-0.087);
var CosB = Math.cos(Math.PI-0.087);

var SinC = Math.sin(Math.PI+0.087);
var CosC = Math.cos(Math.PI+0.087);

canvas.width = 700;
canvas.height = 700;

var half = (canvas.width/2);

function on_enter_frame(){

    SinA = Math.sin(Math.PI+angle);
    CosA = Math.cos(Math.PI+angle);

    SinB = Math.sin(Math.PI-0.087+angle);
    CosB = Math.cos(Math.PI-0.087+angle);

    SinC = Math.sin(Math.PI+0.087+angle);
    CosC = Math.cos(Math.PI+0.087+angle);

    angle+=0.05;

    if (angle>(Math.PI*2)){
        angle=0;
    }

    context.clearRect(0,0,500,500);

    context.fillStyle = "#FFF";

    context.beginPath();
    context.moveTo(half+(SinA*50), half+(CosA*50));
    context.lineTo(half+(SinB*45), half+(CosB*45));
    context.lineTo(half+(SinC*45), half+(CosC*45));
    context.closePath();
    context.fill();
}

setInterval(on_enter_frame,30);

See http://paulirish.com/2011/requestanimationframe-for-smart-animating/ for an explanation of requestAnimationFrame and why to use it.

The reality is that neither requestAnimationFrame nor setInterval will provide rock solid timing, although your chances should be better with requestAnimationFrame . The stutter you're getting might be due to other processes on your computer, or even garbage collection in your current JS process.

Since your loop timing will never be reliable, it's better to base your animation (in this case the position of your orbiting triangle) on actual time (or time elapsed since the previous frame).

I can't see the stutter you're getting, so I don't know whether this will be an improvement, but you can look at a live example of how requestAnimationFrame and elapsed time are used here: http://jsfiddle.net/xpZxy/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM