开发者

Trig problem, choppy movement of a triangle around a circle

开发者 https://www.devze.com 2023-04-05 17:04 出处:网络
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 m

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.

P.S 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.getCo开发者_StackOverflowntext("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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号