I create a game in Javascript using a canvas that requires collision detection, in this case, if the game sprite falls into the field, the player should not be allowed to pass through the field.
I have a global array called blockList that contains all the rectangles drawn on the canvas. It looks like this:
var blockList = [[50, 400, 100, 100]];
And they are drawn to the canvas as follows:
c.fillRect(blockList[0][0], blockList[0][1], blockList[0][2], blockList[0][3]);
I also have a player object that has an update method and a draw method. The update sets the position of the player based on keyboard input, etc., And drawing is used by the main game loop to draw the player on canvas. The player is drawn as follows:
this.draw = function(timestamp) { if(this.state == "idle") { c.drawImage(this.idleSprite, this.idleSprite.frameWidth * this.idleSprite.frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, this.xpos, this.ypos, this.idleSprite.frameWidth, this.idleSprite.frameHeight); if(timestamp - this.lastDraw > this.idleSprite.updateInterval) { this.lastDraw = timestamp; if(this.idleSprite.frameCount < this.idleSprite.frames - 1) { this.idleSprite.frameCount++; } else { this.idleSprite.frameCount = 0; } } } else if(this.state == "running") { var height = 0; if(this.facing == "left") { height = 37; } c.drawImage(this.runningSprite, this.runningSprite.frameWidth * this.runningSprite.frameCount, height, this.runningSprite.frameWidth, this.runningSprite.frameHeight, this.xpos, this.ypos, this.runningSprite.frameWidth, this.runningSprite.frameHeight); if(timestamp - this.lastDraw > this.runningSprite.updateInterval) { this.lastDraw = timestamp; if(this.runningSprite.frameCount < this.runningSprite.frames - 1) { this.runningSprite.frameCount++; } else { this.runningSprite.frameCount = 0; } } } }
Now the player has certain properties: player.xpos , player.ypos , player.width , player.height . The same properties exist for blocks. Therefore, I have everything I need to implement collision detection, I just donβt know how to do it. I tried to do things like:
if(player.x > blockList[0][0] && player.y > blockList[0][1])
but it is far from ideal or reproducible.
Does anyone know of a simple method or function to be able to return true or false based on whether two objects collide?