gpt4 book ai didi

javascript - 如何防止如此频繁地调用更新?

转载 作者:行者123 更新时间:2023-11-29 16:52:37 25 4
gpt4 key购买 nike

我正在使用 ThreeJs 制作俄罗斯方 block 类型的演示。对于渲染,我使用了 requestAnimationFrame。片段:

game.prototype.render = function(){
var thisObj = this;

requestAnimationFrame( function() {thisObj.render();} );

var now = new Date().getTime();
var dt = now - (time || now);
time = now;

this.update(dt);

this.boardMgr.render(dt);
this.renderer.render(this.scene, this.camera);
};

this.update(dt) - 调用 boardMgr.update(dt)

BoardMgr.prototype.update = function(dt) {
if(this.activeBlock == null){
this.activeBlock = this.getNextBlock();
//console.log("letter: " + this.activeBlock.letter);
}

// update active block as per keyboard input
// left/right/falldown
// else
{
this.move(this.activeBlock, DIRECTION.DOWN);
}
};

当我运行它时,方 block 下降得太快(如果我理解正确的话,更新被调用了太多次,因此方 block 更新得同样快)。

如何控制方 block 下落的速度?或者我不应该经常调用 update 吗?处理此问题的正确方法是什么?

代码可以看这里: https://github.com/brainydexter/PublicCode/tree/master/graphics

运动:我有一个 5x5 的网格板,我保持一个板的位置。所以,如果一个方 block 可以向下移动,新的位置就是:(x, y+1)。在渲染时,我根据棋盘位置更新方 block 在世界坐标系中的位置。所以,我总是以 BLOCK_WIDTH 为增量移动 block :

BoardMgr.prototype.render = function(dt) {
for (var i = 0; i < this.blocks.length; i++) {
if(this.blocks[i].visible)
{
this.blocks[i].position.x = (this.BLOCK_WIDTH/2) + ( this.blocks[i].boardPosition.x * this.BLOCK_WIDTH);
this.blocks[i].position.y = (this.BLOCK_WIDTH/2) + ( this.blocks[i].boardPosition.y * this.BLOCK_WIDTH);
}
};
};

最佳答案

编辑

啊。所以我猜你想让方 block 吸附到一个网格上,并让经典的跳动在屏幕上向下移动。最简单的方法是保留自上次更新以来的时间,并且仅在超过特定限制(例如 500 毫秒)时再次移动 block 。

// Wait times between each step
sidestep = 240;
downstep = 500;
fallstep = 80;

BoardMgr.prototype.update = function(dt) {
this.vtimer += dt;
this.htimer += dt;
...

if ( left && this.htimer > sidestep ) {
this.move(this.activeBlock, DIRECTION.LEFT);
this.htimer = 0;
}
if ( right && this.htimer > sidestep ) {
this.move(this.activeBlock, DIRECTION.RIGHT);
this.htimer = 0;
}

if ( ( fall && this.vtimer > fallstep ) || ( this.vtimer > downstep ) ) {
this.vtimer = 0;
this.move(this.activeBlock, DIRECTION.DOWN);
}
};

如果你想让它对左右更加敏感,并且不受横向速度的限制,你可以这样做:

BoardMgr.prototype.update = function(dt) {
this.vtimer += dt;
...

if ( left )
this.move(this.activeBlock, DIRECTION.LEFT);
if ( right )
this.move(this.activeBlock, DIRECTION.RIGHT);

if ( ( fall && this.vtimer > fallstep ) || ( this.vtimer > downstep ) ) {
this.vtimer = 0;
this.move(this.activeBlock, DIRECTION.DOWN);
}
};

关于javascript - 如何防止如此频繁地调用更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34932361/

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