JSFiddle - React, Tailwind, and code Playground
by Raynos
HTML
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
JavaScript
// canvas height
var HEIGHT = 400;
// canvas with
var WIDTH = 640;
// Critter amount
var COUNT = 5;
// base speed of critter
var SPEED = 15;
// Size of critters
var SIZE = 20;
// Time per round
var TIMEOUT = 3000;
// paper object
var paper = Raphael(10, 50, WIDTH, HEIGHT);
// collision algorithm. It's really naive. only checks if mybox is inside box
Raphael.el.collision = function(box) {
var mybox = this.getBBox();
var points = [
[mybox.x, mybox.y],
[mybox.x + mybox.width, mybox.y],
[mybox.x, mybox.y + mybox.height],
[mybox.x + mybox.width, mybox.y + mybox.height]
];
return _.any(points, function(point) {
if (box.x < point[0] && point[0] < box.x + box.width &&
box.y < point[1] && point[1] < box.y + box.height) {
return true;
} else {
return false;
}
});
};
// BBox Mock object for the screen to test for out of bounds
var screen = {
x: 0,
y: 0,
width: WIDTH,
height: HEIGHT
};
var Critter = function() {
// default the speed to something random.
this.speed = SPEED + Math.random()*SPEED;
var loop;
// logic module
var logic = function(food) {
// angle between critter and food
var angle = Raphael.angle(
this.el.getBBox().x,
this.el.getBBox().y,
food.x,
food.y) - 135; // the 135 is the default direction (bottom right)
// get a random speed
var rand = Math.random()*this.speed;
// travel towards the food box by rotating your vector by the angle
var points = this.rotateVector([rand, rand], angle);
// move towards the box
this.el.translate(points[0], points[1]);
// if you hit food you win
if (this.el.collision(food)) {
this.win();
}
// if your not in the screen then your out of bounds
if (!this.el.collision(screen)) {
...