Size() not recognised by PVector?

Hi all,

I’ve been reading about the issue with size() not working in void setup() through version 3, and the fix of moving size() into void settings(). I have run into a similar scenario but it seems to be directly related to using a PVector class.

My code:

class Ship {

  PVector position;
  PVector velocity;

  Ship() {

    position = new PVector(width / 2, height - 10);
  }

  void display() {
    rectMode(CENTER);
    rect(position.x, position.y, 30, 10);
  }
}

Ship s = new Ship();

void setup() {
}

void settings() {
  size(480, 800);
}

void draw() {
  background(0);
  s.display();
}

My ship object only appears at x = 50, y = 90, which makes me think that the vector is getting incorrect size information.

The strange thing is that my sketch is the size I want to be:

I get the same bug whether size() is in setup or settings and I’ve also tried (width / 2, height - 10) as arguments in rect and this gives me what I’m looking for. So it must be an issue with the PVector class, no?

Any suggestions greatly appreciate…

1 Like

Hi,

You are creating a new ship before the width and height of the window is set, that’s why you are getting weird result.

To solve that, you simply need to put the creation of the ship after you set the parameters of your window.

Something like this:

class Ship {

  PVector position;
  PVector velocity;

  Ship() {
    position = new PVector(width / 2, height - 10);
  }

  void display() {
    rectMode(CENTER);
    rect(position.x, position.y, 30, 10);
  }
}

Ship s;

void setup() {
  s = new Ship();
}

void settings() {
  size(480, 800);
}

void draw() {
  background(0);
  s.display();
}
2 Likes

So simple - I wouldn’t have got that in a million years…

Issue solved, thank you jb4x!

1 Like