メニュー 閉じる

019. p5.jsでマウスを重心にしたパーティクルを描いてみる

たくさんのパーティクルはマウス位置との引力関係で動きます。

http://www.velvet-number.com/p5_test/test014/

var p_num;

var p_set = [];

function setup () {

	pixelDensity (displayDensity ());
	createCanvas (windowWidth, windowHeight);
	colorMode (RGB, 256);
	background (255);

	p_num = 2000;

	for (var i = 0; i < p_num; i++) {
		p_set.push (new Particles ());
	}

}

function draw () {

	background (255);

	for (var i = 0; i < p_set.length; i++) {
		p_set[i].update ();
		p_set[i].render ();
	}

}

function Particles () {

	var mass = 0;
	var px = random (width);
	var py = random (height);
	var vx = random (-10, 10);
	var vy = random (-10, 10);
	var ax = 0;
	var ay = 0;
	var sc = 1;
	var distance = 0;

	this.update = function () {

		mass = random (1.0, 40.0);
		ax = -1 * vx * 0.4;
		ay = -1 * vy * 0.4;
		ax += (mouseX - px) * 0.2;
		ay += (mouseY - py) * 0.2;

		distance = dist (mouseX, mouseY, px, py);

		if (distance < 10) {
			sc = 10;
		} else {
			sc = 1 / (distance / 200);
		}

		vx += ax / mass * 0.4;
		vy += ay / mass * 0.4;
		px += vx;
		py += vy;

	}

	this.render = function () {

		stroke (40);
		strokeWeight (1);
		fill (random (255));
		ellipseMode (CENTER);
		ellipse (px, py, 4 * sc, 4 * sc);

	}

}

 

Posted in p5.js , processing