Daniel
Daniel

Reputation: 53

Issue Converting Processing (JAVA based library) into P5.JS code (ECMAScript based library)

I am having issues converting a piece of JAVA based code into ECMAScript/TypeScript, may someone can help. There are two parts I struggle to convert a) a constructor overload I think and b) a self referencing push. Maybe there is a different way to write this?


class Finder {
  PVector location;
  PVector velocity;
  float diameter;
  Pvector origin = new PVector(width / 2, height/2);

  Finder(int x, int y) {
    location = new PVector(width/2, height/2);
    velocity = new PVector(x, y);
    diameter = 8;
  }

  // this is a) where I struggle to convert
  Finder(Finder parent) {
    location = parent.location.get();
    velocity = parent.velocity.get();
    float area = PI*sq(parent.diameter/2);
    float newDiam = sqrt(area/2/PI)*2;
        
    diameter = newDiam;
    parent.diameter = newDiam;
  }

  void update() {
    if(origin.dist(location)> 300){
            // nothing
        } else if (diameter>0.5) {
                location.add(velocity);
                PVector bump = new PVector(random(-1, 1), random(-1, 1));
                bump.mult(0.1);
                velocity.add(bump);
                velocity.normalize();
            
                if (random(0, 1)<0.02) {
                    // this is b) where I struggle to convert
                    paths = (Finder[]) append(paths, new Finder(this));
                }
            }
        }
}

Finder[] paths;

Upvotes: 2

Views: 84

Answers (1)

George Profenza
George Profenza

Reputation: 51837

Regarding part a, treat is a function that returns a copy (new instance with copied properties from argument instance):

(JS doesn't support overloaded constructors, hence simply using a method instead of a constructor should suffice)

e.g.

copy(parent) {
    location = parent.location.copy();
    velocity = parent.velocity.copy();
    let area = PI*sq(parent.diameter/2);
    let newDiam = sqrt(area/2/PI)*2;
        
    diameter = newDiam;
    // this looks a bit sus to me: why should we change the parent ? 
    parent.diameter = newDiam;
  }

Regarding part b I can infer that paths is a Finder[] in the global scope (e.g. main sketch variables). Is so, that will be a plain js array when you port to p5.js and in js arrays are dynamic so you should be able to simply do use paths.push(this.copy()) instead.

(If you want to test in the Processing sketch, swap the Finder[] paths line to ArrayList<Finder> paths = new ArrayList<Finder>() and use paths.add(New Finder(this)); instead paths = (Finder[]) append(paths, new Finder(this));)

Upvotes: 2

Related Questions