碰撞的小球
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 500px;
height: 500px;
border: 1px solid #f40;
margin: 0 auto;
position: relative;
}
.box p {
position: absolute;
background: red;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="box">
</div>
<script src="https://cdn.bootcss.com/underscore.js/1.9.1/underscore-min.js"></script>
<script>
function Ballon() {
this.dom = null;
this.r = 20;
this.x = _.random(this.r,500-this.r);
this.y = _.random(this.r,500-this.r);
do {
this.dx = _.random(-5,5);
this.dy = _.random(-5,5);
}while(this.dx==0&&this.dy==0);
console.log(this.dx,this.dy);
this.init();
arr.push(this);
}
Ballon.prototype.init = function() {
this.dom = document.createElement("p");
document.querySelector(".box").appendChild(this.dom);
this.dom.style.width = (2*this.r) + "px";
this.dom.style.height = (2*this.r) + "px";
this.dom.style.left = (this.x-this.r) + "px";
this.dom.style.top = (this.y-this.r) + "px";
}
Ballon.prototype.move = function() {
this.x += this.dx;
this.y += this.dy;
if (this.x-this.r<0 || this.x+this.r>500) {
this.dx = -this.dx;
} else if(this.y-this.r<0 || this.y+this.r>500) {
this.dy = -this.dy;
}
this.dom.style.left = (this.x-this.r) + "px";
this.dom.style.top = (this.y-this.r) + "px";
}
var arr = [];
new Ballon();
new Ballon();
new Ballon();
new Ballon();
new Ballon();
new Ballon();
setInterval(function() {
_.each(arr,function(item) {
item.move();
})
},10);
</script>
</body>
</html>