javascript面向对象编程——随机混乱碰弹的小球(边缘碰测检验)
Posted 勇敢*牛牛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript面向对象编程——随机混乱碰弹的小球(边缘碰测检验)相关的知识,希望对你有一定的参考价值。
随机混乱碰弹的小球
代码描述:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div1
width: 1000px;
height: 600px;
border: 1px solid #000;
position: relative;
</style>
</head>
<body>
<div class="div1"></div>
<script type="module">
import Main from "./js/Main.js";
new Main();
</script>
</body>
</html>
Circle.js
export default class Circle
elem;
x=0;
y=0;
speedX=5;
speedY=5;
rect;
w=50;
h=50;
static list=new Set();
constructor(color)
this.elem=document.createElement("div");
Object.assign(this.elem.style,
width:this.w+"px",
height:this.h+"px",
backgroundColor:color,
position:"absolute",
borderRadius:"50px",
left:0,
top:0
)
Circle.list.add(this);
appendTo(parent)
if(typeof parent==="string") parent=document.querySelector(parent);
parent.appendChild(this.elem);
this.rect=parent.getBoundingClientRect();
move()
// 如果位置大于父容器的宽度-当前小球的宽度时,让速度变成负数,反方向运动
if(this.x>this.rect.width-this.w || this.x<0)this.speedX=-this.speedX;
if(this.y>this.rect.height-this.h || this.y<0)this.speedY=-this.speedY;
this.x+=this.speedX;
this.y+=this.speedY;
this.elem.style.left=this.x+"px";
this.elem.style.top=this.y+"px";
static update()
for(var item of Circle.list)
item.move();
Utils.js
export default class Utils
static randomSpeed(speed,slowSpeed)
var speed=Math.random()*Math.abs(speed*2)-speed;
return (speed>-slowSpeed && speed<slowSpeed) ? slowSpeed : speed;
static randomColor()
return Array(6).fill(1).reduce(v=>v+(~~(Math.random()*16)).toString(16),"#");
main.js
import Circle from "./Circle.js";
import Utils from "./Utils.js";
export default class Main
constructor()
for(var i=0;i<100;i++)
var c=new Circle(Utils.randomColor());
c.x=~~(Math.random()*950);
c.y=~~(Math.random()*550);
c.speedX= Utils.randomSpeed(5,2);
c.speedY= Utils.randomSpeed(5,2);
c.appendTo(".div1");
this.animation();
animation()
requestAnimationFrame(()=>this.animation());
Circle.update()
以上是关于javascript面向对象编程——随机混乱碰弹的小球(边缘碰测检验)的主要内容,如果未能解决你的问题,请参考以下文章