Collision Detection
by soggydoughnut54
HTML
<canvas id="myCanvas" width="500" height="500" style="border:1px solid red"></canvas>
JavaScript
//access the canvas
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//game variables
var speed = 5;
var key = -1;
var size = 20;
var dirX = 0,
dirY = 0;
var up = 38,
down = 40,
left = 37,
right = 39;
//game objects
var baddie;
var player;
/***************
COLLISION DETECTION
****************/
hitTest = function(object, target) {
//what are return statements?
return object.x <= target.x + target.width && object.x + object.width >= target.x && object.y <= target.y + target.height && object.y + object.height && target.height>= target.y;
return "LOVE IS THE ANSWER";
}
/***************
DRAW GAME
**************/
function draw() {
//background
context.fillStyle = "orange"
context.fillRect(0, 0, canvas.width, canvas.height)
//draw the objects
player.draw();
baddie.draw();
//testing data
context.fillStyle = "black";
context.font = "24px Arial"
context.textAlign = "left"
context.fillText(hitTest(baddie, player), 20, 30);
context.fillText("Player: " + player.x + ", " + player.y, 20, 60);
context.fillText("Baddie: " + baddie.x + ", " + baddie.y, 20, 90);
context.fillText("Range: " + Math.abs(baddie.x-player.x)+", "+Math.abs(baddie.y-player.y), 20, 120);
}
/***************
INITIALIZE GAME
**************/
function init() {
player = new Box(100, 100, 30, "white");
player.move = function() {
this.x += dirX * speed;
this.y += dirY * speed;
}
baddie = new Box(400, 400, 20, "red")
}
function Box(x, y, size, color) {
this.x = x;
this.y = y;
this.spdX = 0;
this.spdY = 0;
this.size = size;
this.color = color
this.width = this.size;
this.height = this.size;
}
Box.prototype.move = function() {
this.spdX = Math.cos(Math.atan2(player.y - this.y, player.x - this.x))*speed/2;
this.spdY = Math.sin(Math.atan2(player.y - this.y, player.x - this.x))*speed/2;
this.x += Math.round(this.spdX);
this.y += Math.round(this.spdY);
if (Math.abs(this.x - player.x) < 50 &&...