Importing p5 in typescript class

Viewed 407

I'm learning some p5 stuff from Coding train, but I'm writing everything in Typescript/webpack project.

I am using p5 as an instance, and my code works fine, but I have a feeling that I'm doing something wrong.

import * as p5 from 'p5';

export class Particlehelper {
  private pos: p5.Vector;
  private vel: p5.Vector;
  private accl: p5.Vector;

  public constructor(p: p5) {
    this.pos = p.createVector(p.random(p.windowWidth), p.random(p.windowHeight));
    // this.vel = p.createVector(0, 0);
    this.vel = p5.Vector.random2D();
    this.accl = p.createVector(0, 0);
  }

What confuses me here is - I'm importing P5 as I need class properties to be of type Vector, but then in order to instanciate vector, I'm passing P5 to the constructor from index file.

particles[i] = new Particlehelper(p);

I have a feeling that is wrong - it sounds to me like I'm doing the same thing twice, but I could not untangle how to use just imported p5 within the class.

As well - I've never seen "public constructor" notation, but linter forced me to add it there - not sure if that is OK or not?

Thanks,

1 Answers

This code is fine. The thing about p5.Vector is that it is a bit odd because it 1) doesn't declare it's actual constructor arguments, 2) may be constructed with a reference to a p5 instance. The reason for this is that there are functions on p5.Vector that take a sketches angleMode into account (DEGREES or RADIANS). When you create a p5.Vector with createVector the resulting vector has a reference to the p5 instance and will respect its angle mode. But you can also create a vector statically, and vectors created that way will not respect the sketches angle mode:

    p.angleMode(p.DEGREES);

    let v1 = p.createVector(1, 0);
    let v2 = p.createVector(0, 1);
    // Result is in degrees
    console.log(v1.angleBetween(v2));

    v1 = new p5.Vector();
    v1.set(1, 0);
    v2 = new p5.Vector();
    v2.set(0, 1);
    // Result is in radians
    console.log(v1.angleBetween(v2));

Note that p5.Vector.random2d is also going to create a vector that uses the default angle mode (radians).

Related