Skip to content

Instantly share code, notes, and snippets.

@ajbogh
Created October 29, 2013 22:32
Show Gist options
  • Save ajbogh/7223887 to your computer and use it in GitHub Desktop.
Save ajbogh/7223887 to your computer and use it in GitHub Desktop.
Attack Bees
//this is a fun script that tracks the mouse position and attacks the mouse with Bees.
//use in a simple HTML file or paste into jsfiddle.net's Javascript panel to test.
var bees = [];
var numbees = 30;
while(bees.length < numbees){
bees[bees.length] = new Bee();
}
//contains everything useful about a bee
function Bee() {
this.body = document.createElement("DIV");
this.body.style.position = "absolute";
this.body.style.left = 0;
this.body.style.top = 0;
this.body.innerText = "B";
this.speed = 20; //5 pixels of movement per turn
}
Bee.prototype.buzz = function(){
var origText = this.body.innerText;
this.body.innerText = "Buzz";
var self = this;
setTimeout(function(){
self.body.innerText = origText;
}, 1000);
};
Bee.prototype.moveTo = function(x,y){
var randX = Math.random(); //makes Bees a little drunk
var randY = Math.random(); //makes Bees a little drunk
var originalX = parseInt(this.body.style.left.replace("px",""), 10);
var originalY = parseInt(this.body.style.top.replace("px",""), 10);
var val, pos, self = this;
pos = Math.random() < 0.5 ? -1 : 1;
if(originalX < x){
pos = 1;
}else if(originalX > x){
pos = -1;
}
val = originalX + (pos * randX * self.speed);
self.body.style.left = (originalX = val)+"px";
pos = Math.random() < 0.5 ? -1 : 1;
if(originalY < y){
pos = 1;
}else if(originalY > y){
pos = -1;
}
val = originalY + (pos * randY * self.speed);
self.body.style.top = (originalY = val)+"px";
};
Bee.prototype.render = function(){
if(!this.body.parent){
document.body.appendChild(this.body);
}
};
Bee.prototype.attack = function(x, y){
var currentPos = [this.body.style.left, this.body.style.top];
this.moveTo(x,y);
};
var mousex = 0, mousey = 0;
document.onmousemove = function(e){
mousex = e.clientX;
mousey = e.clientY;
};
var iteration = 0;
setInterval(function(){
var randBee = Math.floor(Math.random() * bees.length);
bees.map(function(b, idx){
b.render();
//get mouse position and move the b randomly around.
b.attack(mousex, mousey);
if(iteration % 10 == 0){
if(idx === randBee){
b.buzz();
}
iteration = 0;
}
iteration++;
});
}, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment