How can I move the output in p5.js

Viewed 55

Here, which means although not all the they are moving the same direction, I want their face to move forward the way they r moving. and I don't know how to do it so could u help me!. and I don't want long code.

let x = [];
let y = [];
let d = [];
let s = [];
let z = [-1, 1];

function setup() {
  createCanvas(1280, 720);
  colorMode(HSB, 360, 100, 100, 100);

  for (let i = 0; i < 11; i++) {
    x[i] = i * 50;
    d[i] = random(20) * random(z);
    s[i] = random(50, 500);
    y[i] = random(height);
  }
}

function draw() {
  background("black");
  noStroke();

  for (let i = 0; i < 11; i++) {
    fill((i + 1) * 36, 100, 100, 50);
    arc(x[i], y[i], s[i], s[i], radians(30), radians(330), PIE); //pacman shape

    fill(0);
    circle(x[i] + 10, y[i] - s[i] / 4, 10);
    if (i % 2 == 0) {
      x[i] = x[i] + d[i];
      if (x[i] > width) {
        x[i] = 0;
      }
    } else {
      x[i] = x[i] - d[i];
      if (x[i] < 0) x[i] = 1280;
    }
  }
}
1 Answers

I think the easiest solution is to draw different shapes depending on which direction they're going.

I've removed the code:

d[i] = random(20) * random(z); 

// replaced with 
d[i] = random(20)  // so it's just given a random speed which we either add or subtract

which determines the direction, I'm just assuming half are going left and half are going right for the moment.

Next I've added some drawing code which creates the pacman in the other direction:

fill((i + 1) * 36, 100, 100, 50);
arc(x[i], y[i], s[i], s[i], radians(200), radians(150), PIE); //pacman shape
fill(0);
circle(x[i] - 10, y[i] - s[i] / 4, 10);  

Which looks like this:

let y = [];
let d = [];
let s = [];
let x = [];
function setup() {
  createCanvas(1280, 720);
  colorMode(HSB, 360, 100, 100, 100);

  for (let i = 0; i < 11; i++) {
    x[i] = i * 50;
    d[i] = random(20);
    s[i] = random(50, 500);
    y[i] = random(height);
  }
}
function draw() {
  background("black");
  noStroke();

  for (let i = 0; i < 11; i++) {
      if (i % 2 == 0) {
      fill((i + 1) * 36, 100, 100, 50);
      arc(x[i], y[i], s[i], s[i], radians(30), radians(330), PIE); //pacman shape
      fill(0);
      circle(x[i] + 10, y[i] - s[i] / 4, 10);  
      
      x[i] = x[i] + d[i];
      if (x[i] > width) {
        x[i] = 0;
      }
    } else {
      fill((i + 1) * 36, 100, 100, 50);
      arc(x[i], y[i], s[i], s[i], radians(200), radians(150), PIE); //pacman shape
      fill(0);
      circle(x[i] - 10, y[i] - s[i] / 4, 10);  
      x[i] = x[i] - d[i];
      if (x[i] < 0) {
        x[i] = 1280;
      }
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js" integrity="sha512-NxocnqsXP3zm0Xb42zqVMvjQIktKEpTIbCXXyhBPxqGZHqhcOXHs4pXI/GoZ8lE+2NJONRifuBpi9DxC58L0Lw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Related