canvas 小球碰撞

博客尝试用面向对象的方式,借助canvas实现相关内容,可能是小球碰撞屏保,还给出了源码下载链接https://download.csdn.net/download/shishuwei111/11244810 。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

试着用面向对象的方式用canvas去实现一些东西,

主要代码

function Bubble() {}; //构造函数
    Bubble.prototype = {
        init: function () { //基本配置
            this.x = random(0, w); //小球x轴初始位置
            this.y = random(0, h); //小球y轴初始位置
            this.r = random(20, 100); //小球的半径范围
            this.color = 'rgba(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ',' + random(0.1, 1) +')';
            this.vx = random(-1, 1);
            this.vy = random(-1, 1);
			this.isMove = false
        },
        draw: function () { //绘制小球
            canCon.beginPath(); //把笔抬起来,beginPath() 方法开始一条路径,或重置当前的路径。
            canCon.fillStyle = this.color;
            canCon.arc(this.x, this.y, this.r, 0, Math.PI * 2); //圆心的位置,xy,半径,画圆
            canCon.fill();
        },
        move: function () {
			if(this.isMove) {
				this.isMove = false
				return;
			}
			this.x += this.vx;
			this.y += this.vy;
			
			// 检测小球与小球碰撞
			var isCollision = collision(this);
			if (!isCollision) {
			}
			//检测小球与边框碰撞
			
			if (this.x - this.r < 0 || this.x + this.r > w) {
				this.vx = -this.vx
			}
			if (this.y - this.r < 0 || this.y + this.r > h) {
				this.vy = -this.vy
			}
            this.draw();
        }
    }

	function collision (c_ball) {
		var find = false
		var isCollision = false
		for (var ball of aBubble) {
			if(ball != c_ball) {
				var dxv = c_ball.x + c_ball.vx - (ball.x + ball.vx);
				var dyv = c_ball.y + c_ball.vy - (ball.y + ball.vy);
				var distance = Math.sqrt(dxv * dxv + dyv * dyv);

				if (distance <= (c_ball.r + ball.r)) {
					var dvx = c_ball.vx - ball.vx;
					var dvy = c_ball.vy - ball.vy;
					var dx = c_ball.x - ball.x;
					var dy = c_ball.y - ball.y;
					var xx_yy = dx * dx + dy * dy;
					var v_dvx = (dvx * dx * dx + dvy * dx * dy) / xx_yy;
					var v_dvy = (dvy * dy * dy + dvx * dx * dy) / xx_yy;
					c_ball.vx = checkSpeed(c_ball.vx - v_dvx);
					c_ball.vy = checkSpeed(c_ball.vy - v_dvy);
					ball.vx = checkSpeed(ball.vx + v_dvx);
					ball.vy = checkSpeed(ball.vy + v_dvy);
					if (find) {
						//避免当前循环重复移动
						ball.isMove = true
						//避免闪烁
						ball.draw();
					}
					isCollision = true
				}
			} else {
				find = true
			}
		}
		return isCollision;
	}

源码在这里

https://download.csdn.net/download/shishuwei111/11244810

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值