How to use p5.Vector?

Using p5.js library, unable to get the following code to run. am sure that the problem has to do with coding the p5.Vector, but troubleshooting has been unsuccessful. A red ball displays at the center of the canvas, but does not move. Trying to simulate velocity.

var l;
var v;

function setup() {
  createCanvas(1152, 648);
}

function draw() {
  background(255);
  l = new p5.Vector(576, 324);
  v = new p5.Vector(16, 9);
  l.add(v);
  if ((l.x > width) || (l.x < 0)) {
    v.x = v.x * -1;
  }
  if ((l.y > height) || (l.y < 0)) {
    v.y = v.y * -1;
  }
  noStroke();
  fill(255, 0, 0);
  ellipse(l.x, l.y, 100, 100);
  frameRate(30);
}

Answers

  • Answer ✓

    Update Got it to work!

    var l = new p5.Vector(576, 324);
    var v = new p5.Vector(16, 9);
    
    function setup() {
      createCanvas(1152, 648);
    }
    
    function draw() {
      background(255); 
      l.add(v);
      if ((l.x > width) || (l.x < 0)) {
        v.x = v.x * -1;
      }
      if ((l.y > height) || (l.y < 0)) {
        v.y = v.y * -1;
      }
      noStroke();
      fill(255, 0, 0);
      ellipse(l.x, l.y, 100, 100);
      frameRate(30);
    }
    
Sign In or Register to comment.