Vectors and classes

Hello I'm trying to simplify some very clunky code in this example [Vector grid](https://editor.p5js.org/Anna21/sketches/bESH6Jgj1) by using classes. I'm very new to this and I'm sure there's a simple explanation but its eluding me. Here is the code using classes in this link [Classes attempt](https://editor.p5js.org/Anna21/sketches/IW74AgeJM)that I've tried so far. I'd be really grateful if someone has the time to explain where I'm going wrong and if it's indeed possible to do this. Many thanks in advance for your time if you choose to help me with this.
1 Like

this seems to work:



let seed;

function setup() {
  createCanvas(1000,1000);
  seed = new Seed();
}

function draw() {
  background(51);
  seed.show();
}

class Seed {
  
  constructor() {
    this.angle = 0;
    this.angleV = 0;
    this.angleA = -0.0007;
    this.v = 0;
    this.x = 300;
    this.y = 300;
    this.r = 75;
    this.endx = 20;
    this.v = p5.Vector.random3D(); // or 2D 
    this.v = this.v.mult(75);
    //this.v = createVector(random(-100,100))
  }
  
  show() {
      translate(10,10);
      stroke(255);
      line(0,0,this.v.x,this.v.y);      
  }
}//class 
//


Thank you so much! This is helpful.
Best wishes
Jo

1 Like

Hello Again,

I’ve had a pause over the last couple of weeks and I’m trying to create a grid using classes and arrays for the above. I tried this and its not working, is it possible to show me how this works if you’ve got any time. Many thanks for your time in advance.

Best wishes

Jo

https://editor.p5js.org/Anna21/sketches/NwgPfK54e

here

// let v = 0;
// let seed;
let seeds = [];

function setup() {
  createCanvas(1000, 1000);
  background(51);

  for (y = 0; y <= 4; y++) {
    //start a new row by shifting down by 100px
    //translate(0, 100)
    //for (x = 0; x <= width; x = x + 10) {
    //move along to the right in x by 10

    seeds[y] = new Seed();
    //seeds[x] = new Seed ();
  }
}

function draw() {
  for (let y = 0; y < seeds.length; y++) {
    seeds[y].show();
  }
}

class Seed {
  constructor() {
    this.angle = 0;
    this.angleV = 0;
    this.angleA = -0.0007;
    this.v = 0;
    //this.x = 100;
    //this.y = 10;
    //this.r = 100;
    //this.endx = 20;
    this.v = p5.Vector.random2D();
    this.v = this.v.mult(75);
    this.x = this.x + random(-5, 5);
    this.y = this.y + random(-5, 5);

    //move() {
    //this.seed.x = this.seed.x + random(70,70);
    // this.seed.y = this.seed.y + random(-70, 75);
  }

  show() {
    this.v = p5.Vector.random3D();
    this.v = this.v.mult(75);

    //translate(10,10);
    translate(100, 100);
    rotate(this.angle);

    stroke(200);
    line(0, 0, 
         this.v.x, this.v.y);

    this.endx = this.endx + 20;

    //move() {
    //this.seed.x = this.seed.x + random(-5,5);
    //  this.seed.y = this.seed.y + random(-5, 5);
    //}
  }
}
//

Thanks again for your time!

1 Like