粒子(用构造函数制成)在碰撞时扩展并褪色



当用户单击我希望其扩展和褪色的任何粒子时,并在与任何其他粒子发生碰撞时,该粒子也会扩展并褪色。现在,我的问题是我想知道是否有一种方法可以使这些粒子(在这种情况下用构造函数制成(在碰撞时相互影响。链接到Codepen

var bubbles = [];
function setup() {
	frameRate(25);
	// Creates Canvas
	createCanvas(windowWidth, windowHeight);
	//Genrates 100 Particles with random a & y
	for (var i = 0; i < 80; i++) {
		var x = random(width);
		var y = random(height);
		bubbles[i] = new Bubble(x, y);
	}
}
function mousePressed() {
	for (var i = 0; i < bubbles.length; i++) {
		bubbles[i].clicked();
	}
}
function draw() {
	clear();
	//Adds color and motion
	for (var bubble of bubbles) {
		fill(bubble.color.red, bubble.color.green, bubble.color.blue);
		bubble.move();
		bubble.display();
	}
}
function Bubble(x, y) {
	this.x = x;
	this.y = y;
	this.wh = 15;
	this.speedX = random(1, 5);
	this.speedY = random(1, 5);
	//Individual Particle Creation
	this.display = function() {
		noStroke();
		ellipse(this.x, this.y, this.wh, this.wh);
	};
	//Interactivity
	this.clicked = function() {
		var d = dist(this.x, this.y, mouseX, mouseY);
		if (d < 8) {
			this.wh = 100;
		}
	};
	//Randomizes colors
	this.color = {
		red: random(255),
		green: random(255),
		blue: random(255)
	};
	//Particle Motion
	this.move = function() {
		//Motion in X direction
		this.x += this.speedX;
		//Bouncing back on X-axis
		if (this.x > windowWidth || this.x < 0) {
			this.speedX = -this.speedX;
		}
		//Motion in Y Direction
		this.y += this.speedY;
		//Bouncing back on Y-axis
		if (this.y > windowHeight || this.y < 0) {
			this.speedY = -this.speedY;
		}
	};
}
function windowResized() {
	resizeCanvas(windowWidth, windowHeight);
}
::-webkit-scrollbar{
	display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.10/p5.js"></script>

使用嵌套的for循环。

步骤1:在气泡上循环。使用for循环执行此操作。

步骤2:对于每个气泡,在气泡其余的气泡上循环循环(如果您在气泡4上,则从气泡5开始(。使用第一个for循环进行此操作。

步骤3:现在有两个气泡,在它们之间进行碰撞。

如果您难以实现此操作,请开始较小。从一个更简单的程序开始,该程序仅显示两个硬编码的气泡并在它们之间进行碰撞检测。

最新更新