Ask coding questions

← Back to all posts
p5.js query
revolvinglung

Hello! I want to make an infinite grid of dots that move in a random direction offscreen. I thought the best way to do this would be periodic boundary conditions, but I could be wrong. How could I best achieve this?

My code so far is one dot that moves in a random direction. I can make a grid using a for loop, but I cant make the entire grid move. The only way I have managed to do that is by writing out each individual ellipse, obviously I cant make that infinite and its a waste of code/time.

Here's my code for the singular moving dot. How can I make him appear back on screen like in Pac-man?

var x = 250;
var y = 250;
var xspeed = 1;
var yspeed = 1;
var xdirection = 1;
var ydirection = 1;
let rad = 0;
let r,g,b;
let r2,b2,g2;

function setup() {
createCanvas(500,500);
xspeed = random(0,5);
yspeed = random(0,5);
xdirection = random(-1,1);
ydirection = random(-1,1);
rad = random(10,100);
r = random(0,200);
g = 0;
b = random(0,100);
r2 = random(50,200);
g2 = 0;
b2 = random(50,200);
}

function draw() {
background(r2,g2,b2);
noStroke(2);
fill(r,g,b);
ellipse(x,y,rad);
x = x + xspeed xdirection;
y = y + yspeed
ydirection;
}

EDIT:

Okay, so I got almost the desired results by using

if (xpos > width) xpos = 0;
if (xpos < 0) xpos = width;
if (ypos > height) ypos = 0;
if (ypos < 0) ypos = height;

But now there is a stutter whenever the main ellipse goes offscreen. How could I make it smooth? Thanks.

Voters
revolvinglung