Reputation: 731
I am making a tile based game with a traditional method(two for loops) and i am trying to write collision detection but nothing works. I want the blue square to stay in the screen and be on top of the tiles after you hit start. I have encountered a virus looking for a solution. Please help me stack overflow community.
The code:
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>
Upvotes: 0
Views: 474
Reputation: 31040
You could add an if statement to check if the block has hit the wall:
if (person.y<300) person.y ++; else person.y = 0
const context = document.getElementById("canvas").getContext('2d');
const person = new rectangle(100,100,20,20,'blue');
setInterval(update_all,10);
var block_size = 50;
var moving = false;
const tile_map = [
[1,1,1,1,1,1],
[1,0,0,0,0,1],
[1,0,0,0,0,1],
[1,0,0,0,0,1],
[1,0,0,0,0,1],
[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 clear(){
context.clearRect(0,0,300,300);
}
function start(){
moving = true;
}
function stop(){
moving = false;
}
function update_all(){
clear();
person.update();
if(moving != false){
if (person.y<300) person.y ++; else person.y = 0
}
}
#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>
Upvotes: 1