Trying to convert this example into an OOP

Hi, i’m trying to remake this example of Nature of Code (code 1) but instead of drawing in the draw loop, i’m trying to make it as an Object Oriented Program (code 2), however, the behavior of the object is way off. I kinda know what causes the problem, i think the translation is not considering the value of the vectors of the object, then the vector is still been calculated from the top left corner of the screen. I have tried a lot of alternatives, like i can’t even describe what i’ve tried haha, but it didn’t worked out anyway.

Also, i didn’t get it why in the original example it doesn’t work using the “center” vector value for the line start, i know the translation is called after the constructor of the vector is defined as width/2 and height/2, but when i changed it to 0 and 0, it didn’t worked either, shouldn’t this works as the value is the same after all?

Exemple code by @shiffman

void setup() {
  size(640,360);
}

void draw() {
  background(255);
  
  PVector mouse = new PVector(mouseX,mouseY);
  PVector center = new PVector(width/2,height/2);
  mouse.sub(center);

  float m = mouse.mag();
  fill(0);
  noStroke();
  rect(0,0,m,10);
  
  translate(width/2,height/2);
  stroke(0);
  strokeWeight(2);
  line(0,0,mouse.x,mouse.y);
  
}

My try out (the class is called Scan cuz i want to make a radar animation):

Scan s;
color fundo, r, g;

void setup() {
  size (1000, 500);
  
  fundo = color(#01001C);
  r = color(#FF1742);
  g = color(#26FF8E);
}

void draw() {
  s = new Scan(0,0);
  background(#01001C);
  translate(width/2, height/2);
  
  s.display();
}

class Scan {
  PVector origem, dir;
  int maxDist;

  Scan(int tempX, int tempY) {
    dir = new PVector(mouseX, mouseY);
    origem = new PVector(tempX, tempY);
  }

  void display() {
    dir.sub(origem);
    maxDist = height/3;

    stroke(g);
    ellipse(origem.x, origem.y, 10, 10);
    ellipse(dir.x, dir.y, 10, 10);
    dir.setMag(maxDist);
    line(0,0, dir.x, dir.y);
  }
}

Thank you a lot.

Idea of the vector calculatation in the original is to find where mouse is in relation to the center of the screen. You now where the drawing of the line starts. So you need to set your scan there s = new Scan(width/2, height/2);

It’s not recommendable and not very OOP to create a new object at each new draw() cycle. Object creation should be in setup(). If you need to give new values to the object from draw() you use a function to do it.

2 Likes

Yes, i’ve tried to do as you said before this last code i have posted, but didn’t worked either, so this code was the last alternative i have tried, but got it now after your insight, it was a trouble to know where to put each variable, i did put the “dir” vector in the function instead of the constructor and the translate inside the object, that was the tricking part for me.

Thank you!

2 Likes