Currently, I am developing a tile-based game using a traditional method (utilizing two for loops) and struggling with writing collision detection. I want the blue square to remain on the screen and appear on top of the tiles once the start button is clicked. Amid my search for a solution, I've encountered a setback. Any assistance from the Stack Overflow community would be greatly appreciated.
Below is the code snippet:
const context = document.getElementById("canvas").getContext('2d');
const person = new rectangle(100,100,20,20,'blue');
setInterval(update_all,10);
var next_block_x = 0;
var next_block_y = 0;
var block_size = 50;
var moving = false;
const tile_map = [
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[1,0,0,0,0,0],
[1,1,0,0,0,0],
[1,1,1,0,0,0],
[1,1,1,1,1,1]
];
function rectangle(x,y,w,h,col){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.col = col;
this.update = function(){
context.fillStyle = this.col;
context.fillRect(this.x,this.y,this.w,this.h);
context.stroke();
}
}
function block(x,y,col){
this.x = x;
this.y = y;
this.col = col;
context.fillStyle = this.col;
context.fillRect(this.x,this.y,block_size,block_size);
context.stroke();
}
function update_tile_map(){
for(i=0;i<tile_map.length;i++){
for(var j=0;j<tile_map[i].length;j++){
if(tile_map[i][j] == 1){
new block(next_block_x,next_block_y,'red');
}
next_block_x += block_size;
}
next_block_x = 0;
next_block_y += block_size
}
next_block_x = 0;
next_block_y = 0;
}
function clear(){
context.clearRect(0,0,300,300);
}
function start(){
moving = true;
}
function stop(){
moving = false;
}
function update_all(){
clear();
update_tile_map();
person.update();
if(moving != false){
person.y ++;
}
}
#canvas{
background-color:lightgrey;
border: 4px solid grey;
}
<button onclick='start()'>START</button>
<button onclick='stop()'>STOP</button>
<canvas id="canvas" width='300' height='300'></canvas>