小球碰撞(面向对象)

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8" />
	<title>01小球碰撞(面向对象版)</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);
		//定位父级及样式设置
		parentObj.style.position = "relative";
		this.obj = document.createElement("div");
		parentObj.appendChild(this.obj);
		this.obj.style.position = "absolute";
		//随机半径(因为宽度高度都是需要使用this.r的,所以应该定义在宽度高度之前)
		this.r = ranNum(20, 50);
		this.obj.style.width = this.obj.style.height = this.r * 2 + "px";
		this.obj.style.borderRadius = "50%";

		//随机颜色
		this.obj.style.background = ranCol();
		//随机位置
		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";

		//随机速率大小及方向
		//易错点:如果把代码错写成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);

	}
	//设置小球的方法
	//注意:当函数在等号的右侧时,必须使用分号结束.
	Ball.prototype.move = function () {
		//注意:下面代码可以省略window
		window.setInterval(doMove, 10);
		//改变this的指向
		var _this = this;

		function doMove() {
			//思考:为什么这里的this指代window对象?答: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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CHH5431

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值