I'm currently working on a Tetris demo using ThreeJs. To render the game, I am utilizing requestAnimationFrame
. Below is a snippet of the code:
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) - invokes 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 based on keyboard input
// left/right/falldown
// otherwise
{
this.move(this.activeBlock, DIRECTION.DOWN);
}
};
When testing the demo, I noticed that the blocks fall too quickly. It seems like the update function is being called too frequently, causing the blocks to update rapidly. How can I regulate the speed at which the blocks fall? Should I reduce the frequency of update calls? What is the optimal way to address this issue?
You can view the full code here: https://github.com/brainydexter/PublicCode/tree/master/graphics
Movement: The game features a 5x5 grid-board, where each block has a specific board position. When a block can move downwards, its new position is calculated as: (x, y+1). During rendering, the block's position in the world coordinate system is updated based on the board position. Hence, blocks move in increments of BLOCK_WIDTH:
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);
}
};
};