Skip to content

Instantly share code, notes, and snippets.

@baniol
Created March 30, 2014 19:27
Show Gist options
  • Save baniol/9878277 to your computer and use it in GitHub Desktop.
Save baniol/9878277 to your computer and use it in GitHub Desktop.
avoiding collision, canvas, animation, ai
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bouncing 1</title>
<link rel="stylesheet" href="./include/style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="./include/utils.js"></script>
<script src="./classes/ball.js"></script>
<script>
window.onload = function() {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
ball = new Ball(10, 'blue'),
vx = 1,
vy = 1;
ball.x = 100;
ball.y = 100;
var Ball2 = new Ball(10, 'green');
var staticBall = function () {
Ball2.x = canvas.width / 2;
Ball2.y = canvas.height / 2;
Ball2.draw(context);
};
var checkCollision = function (obj) {
var radius = 50;
var dy = Ball2.y - obj.y;
var dx = Ball2.x - obj.x;
if ((dx <= radius && dy <= radius) && (dy > -radius && dx > -radius)) {
return {x: dx, y: dy};
} else {
return false;
}
};
var vLenght = function (one, two) {
return Math.sqrt(Math.abs(one.x * two.x + one.y * two.y));
};
(function drawFrame() {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
staticBall();
var distance = checkCollision(ball);
if (distance) {
var l = vLenght(distance, ball);
var u = {x: distance.x / l, y: distance.y / l};
}
else {
var u = {x: 0, y: 0};
}
if (ball.x < 380) {
ball.x += vx + (u.x * 10);
ball.y += vy;
}
ball.draw(context);
}());
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment