Skip to content
Advertisement

p5: Using Sine wave in WEBGL to change y-axis

I have some spheres that I want to move straight on the x axis with only their y-axis changing based on the sine wave (you know the up and down yo-yo pattern). It is pretty simple in 2d but for some reason, in WEBGL, the angle changes in the sin function is not working for this.y.

let particles = [];
let quantity = 20;

function setup() {
  createCanvas(300, 300, WEBGL);

  for (let i = 0; i < quantity; i++) {
    let particle = new Particle();
    particles.push(particle);
  }
}

function draw() {
  background(15);
  orbitControl();
  directionalLight([255], createVector(0, 0, -1));
  translate(-width / 2, 0);

  particles.forEach(particle => {
    particle.update();
    particle.edges();
    particle.show();
  });
};


// particle.js
function Particle() {
  this.angle = 0;
  this.r = 10;
  this.x = random(width);
  this.y = sin(this.angle) * 200; // I am changing this angle later but it's not working
  this.z = random(-50, 50);
  this.pos = createVector(this.x, 0, 0);
  this.vel = createVector(2, this.y, 0);

  this.update = function() {
    this.pos.add(this.vel);
    this.vel.limit(4);
    this.angle += 3;
    // print(this.pos);
  }

  this.edges = function() {
    if (this.pos.x >= width) {
      this.pos.x = 0;
    }
  }

  this.show = function() {
    noStroke();
    push();
    translate(this.pos.x, this.pos.y, 0);
    sphere(this.r);
    pop();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>

Advertisement

Answer

You only call sin one time in the construtor. You probably meant to apply it to this.y on every frame based on this.angle, or some other incrementing value. Also, there are duplicate vectors; pick either an x/y pair or use a vector x/y, but not both.

let particles = [];
let quantity = 20;

function setup() {
  createCanvas(300, 300, WEBGL);

  for (let i = 0; i < quantity; i++) {
    let particle = new Particle();
    particles.push(particle);
  }
}

function draw() {
  background(15);
  orbitControl();
  directionalLight([255], createVector(0, 0, -1));
  translate(-width / 2, 0);

  particles.forEach(particle => {
    particle.update();
    particle.edges();
    particle.show();
  });
};


// particle.js
function Particle() {
  this.angle = 0;
  this.r = 10;
  this.x = random(width);
  this.y = 0;

  this.update = function() {
    this.angle += 0.05;
    this.y = sin(this.angle) * 100;
  }

  this.edges = function() {
    if (this.x >= width) {
      this.x = 0;
    }
  }

  this.show = function() {
    noStroke();
    push();
    translate(this.x, this.y, 0);
    sphere(this.r);
    pop();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement