JS初练——弹弹球与墙壁碰撞处理实例
最近在js学习中,发现关于碰撞反弹的问题,笔者觉得非常有趣,就浅浅了解了一下相关原理,如有不足,可以在评论区批评指正,碰撞处理中对于小球与其他形状的处理,主要取决于小球与其他正形状的相切问题(复杂图形笔者能力有限),本次案例就以小球与边界问题来做案例。
代码:
#body { margin: 10px; border: 20px solid rgb(80, 38, 78); padding: 0px; width: 700px; height: 700px; background-color: rgb(60, 247, 255);}#box { margin: 0px; padding: 0px; width: 700px; height: 700px; overflow: hidden; background-color: rgb(254, 255, 67); float: left;}.ball { position: absolute; border: 1px solid black; border-radius: 50%; text-align: center; line-height: 20px;} 弹弹球 var timer;var colorList = ["#FFFF99", "#B5FF91", "#94DBFF", "#FFBAFF", "#FFBD9D", "#C7A3ED", "#CC9898", "#8AC007", "#CCC007"];var colorNum = colorList.length;var ballList = new Array();var timerList = new Array();class ball { constructor(_id, _r, _x, _y, _c, _vx, _vy) { this.id = _id; this.r = _r; this.x = _x; this.y = _y; this.c = _c; this.vx = _vx; this.vy = _vy; } addBall(obj) { var ball = document.createElement("div"); ball.className = "ball"; ball.id = this.id; ball.style.height = this.r + "px"; ball.style.width = this.r + "px"; ball.style.left = this.x + "px"; ball.style.top = this.y + "px"; ball.style.backgroundColor = this.c; //ball.textContent = ball.id; obj.appendChild(ball); } move() { var nextx = this.x + this.vx; var nexty = this.y + this.vy; if (nextx 10 + 700 - this.r + 20) this.vx = -this.vx; if (nexty 10 + 700 - this.r + 20) this.vy = -this.vy; this.x = this.x + this.vx; this.y = this.y + this.vy; this.vx = this.vx + iax + this.vx * ikx; this.vy = this.vy + iay + this.vy * iky; //console.log("new position "+this.x+"\t"+this.y+"\t\t"+"new velocity "+this.vx+"\t"+this.vy); var thisBall = document.getElementById(this.id); thisBall.style.left = this.x + "px"; thisBall.style.top = this.y + "px"; }}var ballCount = 0;//时间间隔var dt = 10;//重力场var iax = 0, iay = 0.05;//阻力系数var ikx = 0, iky = 0;function createBall(obj) { var e = event || window.event; div_x = e.clientX; div_y = e.clientY; ballCount++; _id = "ball" + ballCount; _r = parseInt(Math.random() * 50 + 25); _x = div_x - _r / 2; _y = div_y - _r / 2; _c = colorList[parseInt(Math.random() * colorNum)]; _theta = parseInt(Math.random() * 180); _v = 5; _vx = _v * Math.cos(_theta); _vy = _v * Math.sin(_theta); ballList[ballCount] = new ball(_id, _r, _x, _y, _c, _vx, _vy); console.log("ball created " + ballList[ballCount]); ballList[ballCount].addBall(obj); console.log(ballList);}function moving() { for(i=1;i<ballList.length;i++){ ballList[i].move(); }}function keepMoving() { clearInterval(timer); timer = setInterval("moving()", dt);}