Single circle bouncing around:
let x;
let y;
let speedX;
let speedY;
function setup() {
createCanvas(800, 800);
x = random(width);
y = random(height);
speedX = random(-3, 3);
speedY = random(-3, 3);
}
function draw() {
background(220);
circle(x, y, 50);
x += speedX;
y += speedY;
if (x < 0 || x > width) {
speedX *= -1;
}
if (y < 0 || y > height) {
speedY *= -1;
}
}
Same thing implemented with a class:
let myParticle;
function setup() {
createCanvas(800, 800);
myParticle = new Particle();
}
function draw() {
background(220);
myParticle.draw();
}
class Particle {
constructor() {
this.x = random(width);
this.y = random(height);
this.speedX = random(-3, 3);
this.speedY = random(-3, 3);
}
draw() {
circle(this.x, this.y, 50);
this.x += this.speedX;
this.y += this.speedY;
if (this.x < 0 || this.x > width) {
this.speedX *= -1;
}
if (this.y < 0 || this.y > height) {
this.speedY *= -1;
}
}
}
Array of objects
let particles = [];
function setup() {
createCanvas(800, 800);
for (let i = 0; i < 100; i++) {
particles.push(new Particle());
}
}
function draw() {
background(220);
for (let particle of particles) {
particle.draw();
}
}
class Particle {
constructor() {
this.x = random(width);
this.y = random(height);
this.speedX = random(-3, 3);
this.speedY = random(-3, 3);
}
draw() {
circle(this.x, this.y, 50);
this.x += this.speedX;
this.y += this.speedY;
if (this.x < 0 || this.x > width) {
this.speedX *= -1;
}
if (this.y < 0 || this.y > height) {
this.speedY *= -1;
}
}
}
Particle interaction
let particles = [];
function setup() {
createCanvas(800, 800);
for (let i = 0; i < 100; i++) {
particles.push(new Particle());
}
}
function draw() {
background(220);
for (let particle of particles) {
particle.draw();
}
}
class Particle {
constructor() {
this.x = random(width);
this.y = random(height);
this.speedX = random(-3, 3);
this.speedY = random(-3, 3);
}
draw() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x < 0 || this.x > width) {
this.speedX *= -1;
}
if (this.y < 0 || this.y > height) {
this.speedY *= -1;
}
circle(this.x, this.y, 10);
for (let particle of particles) {
let d = dist(this.x, this.y, particle.x, particle.y);
if (d > 0 && d < 100) {
line(this.x, this.y, particle.x, particle.y);
}
}
}
}
Other resources:
- Nature of Code
- https://natureofcode.com/book/chapter-1-vectors/ - Introduction to modelling natural systems in Java with Processing
- Nature of Code examples with p5.js: https://github.com/nature-of-code/noc-examples-p5.js
- https://thecodingtrain.com/learning/nature-of-code/ - New version of the book as video tutorials and in p5.js
- https://natureofcode.com/book/chapter-1-vectors/ - Introduction to modelling natural systems in Java with Processing