gpt4 book ai didi

javascript - 两个不同的计算和绘图循环

转载 作者:行者123 更新时间:2023-12-03 07:59:41 27 4
gpt4 key购买 nike

因此,我一直在寻找提高 Canvas 动画的运动平滑度和性能的方法。

在一些游戏开发论坛上快速谷歌一下,建议使用两种不同的循环,一种用于计算,一种用于绘图......示例代码如下所示:

function mainLoop() {
// all of your logic goes here, moving positions, checking inputs, etc...
// I guess it's proper to put all drawing to "off screen" canvases here too.
...
setTimeout(mainLoop, 1000 / desiredFPS);
}

function drawingLoop() {
//only drawing commands to the visible canvas goes here
...
requestAnimationFrame(drawingLoop);
}

//when your assets are loaded you just simply make a
//call to each loop to get them started...
mainLoop();
drawingLoop();

这实际上是最好的方法吗?

我目前的所有逻辑和绘图都在同一个循环中。我认为两个不同的循环实际上会降低帧速率以及所有的平滑度?

我目前的方法更像是这样:

function loop() {
calculate(); // calculate everything
draw(); // draw everything
requestAnimationFrame(loop);
}
loop();

为什么建议做两个不同的循环,这样做有什么优点和缺点吗?

最佳答案

如果您想提高性能并将计算与实际渲染分离,您应该看看 MDN 上的 WebWorkers或HTML5 rocks 。它们基本上都是线程,可以让您从主线程卸载一些工作。

但是当谈到性能时,您可能应该看看 Chrome 中的性能工具,这可能会帮助您揭穿代码中其他重要部分的真相。看看doc for the CPU profiling

关于javascript - 两个不同的计算和绘图循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34649024/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com