Nataly J
Nataly J

Reputation: 45

Why won't my ball bounce off a block?

I cannot figure out what I'm doing wrong. I'm checking which side the ball has hit and changing the x/y components appropriately but it just goes straight through the box. Any help? Thanks.

PVector p = new PVector(0, 0); //position
PVector v = new PVector(5, 10); //velocity

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

void draw()
{
  background(0);
  rect(250, 250, 200, 100);
  ellipse(p.x, p.y, 20, 20);
  p.add(v);
  if (p.x < 0 || p.x > width) // ball hit sides of window
  {
    v.x = -v.x;
  }
  if (p.y < 0 || p.y > height) // ball hit top/bottom of window
  {
    v.y = -v.y;
  }
  if (p.x > 250 && p.x < 450 && p.y > 250 && p.y < 350) // ball is inside box
  {
    if (p.y - v.y <= 250 || p.y + v.y >= 350) // ball came from above/below
    {
      v.y = -v.y;
    } 
    if (p.x - v.x <= 250 || p.x + v.x >= 450) // ball came from sides
    {
      v.x = -v.x;
    }
  }
}

Upvotes: 0

Views: 111

Answers (1)

used47
used47

Reputation: 51

You're initial set up is actually almost perfect. I only changed 2 things in the the third if statement (the if statement which handles the collision with the rectangle).

-Added/subtracted the width/height of the dot to the x/y of the dot. Because of this you will not just use the center of the dot for the collision detection but the whole dot.

-Changed > or < in >= <=, because you're working with increments of 5 and 10 it is almost certain that the dot has an X which is the same as either 250 or 450. Same for the Y.

Here is my version of the complete script, hope it helps!

PVector p = new PVector(0, 0); //position
PVector v = new PVector(5, 10); //velocity

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

void draw()
{
  background(0);
  rect(250, 250, 200, 100);
  ellipse(p.x, p.y, 20, 20);
  p.add(v);
  if (p.x < 0 || p.x > width) // ball hit sides of window
  {
    v.x = -v.x;
  }
  if (p.y < 0 || p.y > height) // ball hit top/bottom of window
  {
    v.y = -v.y;
  }
  if (p.x + 10 >= 250 && p.x - 10 <= 450 && p.y + 10 >= 250 && p.y - 10 <= 350) // ball is inside box
  {
    if (p.y  <= 250 || p.y  >= 350) // ball came from above 
    {
      v.y = -v.y;
    } 
    if (p.x <= 250 || p.x >= 450) // ball came from sides
    {
      v.x = -v.x;
    }
  }
}

Upvotes: 1

Related Questions