Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
</head>
<body>
<div style='position:absolute;top:100px;left:100px;height:350px;width:350px;overflow:hidden;background-Color:blue;'>
<div id='m1' style='position:absolute;top:2px;left:2px;height:50px;width:50px;overflow:hidden;background-Color:red;'></div>
<div id='m2' style='position:absolute;top:2px;left:2px;height:50px;width:50px;overflow:hidden;background-Color:green;'></div>
</div>
<script type="text/javascript">
/*<![CDATA[*/
function MoveIt(o){
this.obj=document.getElementById(o.ID);
this.w=o.MaxX;
this.h=o.MaxY;
this.ms=o.Timer||40
this.min=o.MinSpeed||1;
this.max=o.MaxSpeed||5;
this.vel=Math.round(this.min+(this.max-this.min)/2);
this.y = 2;
this.x = 2;
var dir=[45,135,225,315];
this.dir = dir[Math.floor(Math.random()*4)]; //direction.
this.acc = o.Acceleration||2; //acceleration.
this.newacc = [1,0,1];
this.sev = 0;
this.newsev = [1,-1,2,-2,0,0,1,-1,2,-2];
//counters.
this.c1 = 0; //time between changes.
this.c2 = 0; //new time between changes.
this.moveit();
}
MoveIt.prototype={
moveit:function(){
var vb,hb,dy,dx,curr,oop=this;
if (this.acc == 1) this.vel +=0.05;
if (this.acc == 0) this.vel -=0.05;
if (this.vel >= this.max) this.vel = this.max;
if (this.vel <= this.min) this.vel = this.min;
this.c1++;
if (this.c1 >= this.c2){
this.sev = this.newsev[Math.floor(Math.random()*this.newsev.length)];
this.acc = this.newacc[Math.floor(Math.random()*this.newacc.length)];
this.c2 = Math.floor(20+Math.random()*50);
this.c1=0;
}
curr = this.dir+=this.sev;
dy = this.vel * Math.sin(curr*Math.PI/180);
dx = this.vel * Math.cos(curr*Math.PI/180);
this.y+=dy;
this.x+=dx;
//horizontal-vertical bounce.
vb = 180-this.dir;
hb = 0-this.dir;
//Corner rebounds?
if ((this.y < 1) && (this.x < 1)){this.y = 1; this.x = 1; this.dir = 45;}
if ((this.y < 1) && (this.x > this.w)){this.y = 1; this.x = this.w; this.dir = 135;}
if ((this.y > this.h) && (this.x < 1)){this.y = this.h; this.x = 1; this.dir = 315;}
if ((this.y > this.h) && (this.x > this.w)){this.y = h; this.x = this.w; this.dir = 225;}
//edge rebounds.
if (this.y < 1) {this.y = 1; this.dir = hb;}
if (this.y > this.h) {this.y = this.h; this.dir = hb;}
if (this.x < 1) {this.x = 1; this.dir = vb;}
if (this.x > this.w) {this.x = this.w; this.dir = vb;}
this.obj.style.top = this.y + 'px';
this.obj.style.left = this.x + 'px';
setTimeout(function(){ oop.moveit(); },this.ms);
}
}
new MoveIt({
ID:'m1',
MaxX:300,
MaxY:300,
Timer:40,
MinSpeed:1,
MaxSpeed:5,
Acceleration:2
});
new MoveIt({
ID:'m2',
MaxX:300,
MaxY:300,
Timer:40,
MinSpeed:5,
MaxSpeed:15,
Acceleration:5
});
/*]]>*/
</script>
</body>
</html>
Bookmarks