小球碰撞(面向对象)
生活随笔
收集整理的這篇文章主要介紹了
小球碰撞(面向对象)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
<!DOCTYPE html>
<html><head><meta charset="utf-8" /><title>01小球碰撞(面向?qū)ο蟀?</title><style type="text/css">* {margin: 0;padding: 0;}#wrapper {width: 600px;height: 400px;margin: 0 auto;border: 4px solid gold;}</style>
</head><body><div id="wrapper"></div>
</body></html>
<script type="text/javascript">function Ball(parentObj) {if (!parentObj) {return;}//console.log(parentObj);console.log(this);//定位父級(jí)及樣式設(shè)置parentObj.style.position = "relative";this.obj = document.createElement("div");parentObj.appendChild(this.obj);this.obj.style.position = "absolute";//隨機(jī)半徑(因?yàn)閷挾雀叨榷际切枰褂胻his.r的,所以應(yīng)該定義在寬度高度之前)this.r = ranNum(20, 50);this.obj.style.width = this.obj.style.height = this.r * 2 + "px";this.obj.style.borderRadius = "50%";//隨機(jī)顏色this.obj.style.background = ranCol();//隨機(jī)位置this.x = ranNum(0, parentObj.clientWidth - this.r * 2);this.y = ranNum(0, parentObj.clientHeight - this.r * 2);//位置this.obj.style.left = this.x + "px";this.obj.style.top = this.y + "px";//隨機(jī)速率大小及方向//易錯(cuò)點(diǎn):如果把代碼錯(cuò)寫成this.speedX = ranNum(5, 10) * ranNum(0, 1) ? -1 : 1; 那么系哦啊求的速度就只能為-1或者1.this.speedX = ranNum(2, 5) * (ranNum(0, 1) ? -1 : 1);this.speedY = ranNum(2, 5) * (ranNum(0, 1) ? -1 : 1);}//設(shè)置小球的方法//注意:當(dāng)函數(shù)在等號(hào)的右側(cè)時(shí),必須使用分號(hào)結(jié)束.Ball.prototype.move = function () {//注意:下面代碼可以省略windowwindow.setInterval(doMove, 10);//改變this的指向var _this = this;function doMove() {//思考:為什么這里的this指代window對(duì)象?答:setinterval是Window的一種方法.//console.log(this);_this.x += _this.speedX;_this.y += _this.speedY;//左邊界控制if (_this.x <= 0) {_this.x = 0;//改變方向_this.speedX *= -1;}//右邊界控制if (_this.x >= _this.obj.parentElement.clientWidth - _this.r * 2) {_this.x = _this.obj.parentElement.clientWidth - _this.r * 2;_this.speedX *= -1;}//上邊界控制if (_this.y <= 0) {_this.y = 0;//改變方向_this.speedY *= -1;}//下邊界控制if (_this.y >= _this.obj.parentElement.clientHeight - _this.r * 2) {_this.y = _this.obj.parentElement.clientHeight - _this.r * 2;_this.speedY *= -1;}_this.obj.style.left = _this.x + "px";_this.obj.style.top = _this.y + "px";}};function ranNum(x, y) {return Math.floor(Math.random() * (y - x + 1) + x);}function ranCol(x, y) {var red = ranNum(0, 255);var green = ranNum(0, 255);var blue = ranNum(0, 255);return "rgb(" + red + "," + green + "," + blue + ")";}var oWrap = document.getElementById("wrapper");for (var i = 0; i < 20; i++) {//把小球添加到wrapper中var ball = new Ball(oWrap);ball.move();}
</script>
總結(jié)
以上是生活随笔為你收集整理的小球碰撞(面向对象)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Apache Commons BeanU
- 下一篇: acpi_hardware_id可以通过