I'm trying to create a collision detection system for an HTML 5 game that I'm building for my school project.
I have a moving square sprite (character) set up with a function that adds another stationary square sprite (obstacle) in the path of the character sprite.
I want to make a system where the character sprite stops when it touches the obstacle sprite.
Check out a live example - JsFiddle
My Code:
<p><canvas id="canvas" width="500" height="500"></p>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var positionX = 100.0;
var positionY = 350.0;
var velocityX = 4.0;
var velocityY = 0.0;
var gravity = 0.5;
var onGround = false;
window.addEventListener("mousedown", StartJump, false);
window.addEventListener("mouseup", EndJump, false);
Loop();
function StartJump() {
if (onGround) {
velocityY = -12.0;
onGround = false;
}
}
function EndJump() {
if (velocityY < -6.0)
velocityY = -6.0;
}
function Loop() {
Update();
Render();
window.setTimeout(Loop, 33);
}
function Update() {
velocityY += gravity;
positionY += velocityY;
positionX += velocityX;
if (positionY > 300.0) {
positionY = 300.0;
velocityY = 0.0;
onGround = true;
}
if (positionX < 10 || positionX > 500)
velocityX *= -1;
}
function drawSquare() {
ctx.beginPath();
ctx.rect(300, 270, 30, 30);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();
}
function Render() {
ctx.clearRect(0, 0, 500, 500);
drawSquare();
ctx.beginPath();
ctx.moveTo(0, 300);
ctx.lineTo(500, 300);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(positionX - 10, positionY - 20);
ctx.lineTo(positionX + 10, positionY - 20);
ctx.lineTo(positionX + 10, positionY);
ctx.lineTo(positionX - 10, positionY);
ctx.closePath();
ctx.stroke();
}
< /script>