フロントエンドの環境進化に伴い、ES6 syntaxでもp5.jsを書くことができるようになってきました。パーティクルを動かしてみます。
準備
ビルド環境
省略します。それぞれのやり方でES6が書ける環境を構築しましょう
インストール
npm install --save p5
ファイル構成
3つのファイルを同じ階層に配置しています。
- sketch.js
- Particle.js
- ParticleSystem.js
実装
インスタンスモード
インスタンスモードを使います。
Instantiation Cases · processing/p5.js Wiki
sketch.js
sketch.js
import P5 from "p5";
import ParticleSystem from "./ParticleSystem";
const sketch = (p) => {
var system;
p.preload = function() {
}
p.setup = function() {
p.createCanvas(p.windowWidth, p.windowHeight);
p.background(255);
system = new ParticleSystem();
//パーティクルの数
var num = 500;
for(var i = 0; i < num; i++) {
var l = p.createVector(p.random(p.windowWidth), p.random(p.windowHeight));
system.addParticle(p, l);
}
}
p.draw = function() {
p.background(255);
system.run();
}
}
new P5(sketch);
ParticleSystem.js
ParticleSystem.js
import Particle from "./Particle";
export default class ParticleSystem {
constructor() {
this.particles = [];
}
addParticle(p, location) {
this.particles.push(new Particle(p, location));
}
run() {
this.particles.forEach((particle) => {
particle.run();
})
}
}
Particle.js
Particle.js
export default class Particle {
constructor(p, location) {
var v = 1;
this.p = p;
this.acceleration = this.p.createVector(0, 0);
this.velocity = this.p.createVector(p.random(-v, v), p.random(-v, v));
this.location = location.copy();
this.diameter = 5;
this.wall = {
top: this.diameter / 2,
right: this.p.windowWidth - this.diameter / 2,
bottom: this.p.windowHeight - this.diameter / 2,
left: this.diameter / 2
}
}
run() {
this.update();
this.borders();
this.display();
}
update() {
this.velocity.add(this.acceleration);
this.location.add(this.velocity);
}
display() {
this.p.noStroke();
this.p.fill(0);
this.p.ellipse(this.location.x, this.location.y, this.diameter, this.diameter);
}
//壁の当たり判定
borders() {
if (this.location.y < this.wall.top) {
this.location.y = this.wall.top;
this.velocity.y *= -1;
}
if (this.location.x > this.wall.right) {
this.location.x = this.wall.right;
this.velocity.x *= -1;
}
if (this.location.y > this.wall.bottom) {
this.location.y = this.wall.bottom;
this.velocity.y *= -1;
}
if (this.location.x < this.wall.left) {
this.location.x = this.wall.left;
this.velocity.x *= -1;
}
}
}
所感
constructorにpを渡して,this.pと書くのがダルいような。。。 良い方法があればご教授ください