PVector transformation


#1

Hello there, in a recent tutorial of “the coding train” with Daniel Shiffman I was learning about PVector.

In the video (https://www.youtube.com/watch?v=7nTLzLf7jUg) he transforms a simple bouncing ball sketch with variables like xPosition, yPosition and xSpeed, ySpeed to a sketch that uses vectors.

I thought I had understood everything and applied everything he did in my own program, but for some reason my ball does not move. I realise my structure is different as I do not have a separate class for the ball, but since it worked with xSpeed and ySpeed etc… I don’t see why it wouldn’t here.

Any suggestions on how to fix this problem are welcome.

int ballSize = 50;
PVector location;
PVector velocity;
int hitcount = 0;

void setup() {
  size(600, 400);
}

void draw() {
  location = new PVector(100, 200);
  velocity = new PVector(2, 3);
  background(51);
  drawBall();
  text("Hits: "+ hitcount, 100, 100);
}

void drawBall() {
  ellipse(location.x, location.y, ballSize, ballSize);
  location.add(velocity);
  if ((location.x>(width-(ballSize/2))) || (location.x < (0+(ballSize/2)))) {
    velocity.x = velocity.x * -1;
  }
  if ((location.y>(height-(ballSize/2))) || (location.y < (0 + (ballSize/2)))) {
    velocity.y = velocity.y * -1;
  }
}

void mouseClicked() {
  print("click");
  if (dist(mouseX, mouseY, location.x, location.y)<=40) {
    hitcount++;
  }
}


#2

Hi @Ben1,
First off, when you declare values for variables like static vectors (not changing value), it is stylishly best to do it elsewhere than void draw(). void setup() is a great place to do this:

void setup() {
  size(600, 400);
  location = new PVector(100, 200);
  velocity = new PVector(2, 3);
}

So try rectifying this stilish mistake. :slight_smile:

OH, it fixed it. Do you understand why?

Before you rectified this misplacement of static vectors you tried to set location at two different places at once. In the top of draw you let location be a PVector with the values (100, 200), whereas drawBall sets the new values as (102, 203).


#3

That’s actually the cause of the bug. It’s resetting the location every frame.


#4

First off, when you declare values for variables like static vectors (not changing value), it is stylishly best to do it elsewhere than void draw() . void setup() is a great place to do this:

Of coooourrrseeee,

Sticking to convention is an even better idea than it used to be.

It would have probably taken me quite a while to realise void draw is resetting the vectors echt time. Thanks a lot! @Pyrros