Could someone please explain why my code is not working the way I expect it to be? Pinball

69 views Asked by At

I am trying to create a "pinball" in Java that bounces an image of a ball within the frame, and my bottom edge is reacting very weirdly. Instead of sending my ball in the opposite direction, my ball is following the bottom edge.

I believe the error in the code is within the third block (which is asterisked), but I am unable to tell what is causing this.

public void move(double rightEdge, double bottomEdge)
{
  setX(getX()+ dx);                  // move horizontally

  if(getX() >= rightEdge - getRadius())  //hit right edge
  {
     setX(rightEdge - getRadius());
     dx = dx * -1; 
  }

  if(getX() - getRadius() <= 0)
  {
     setX(getRadius());
     dx= dx*-1;
  }

  setY(getY() + dy);


 **if(getY() - getRadius() <=0)
   {
      setY(getRadius());
      dy = dy * -1; 
   }**


   if(getY() >= bottomEdge - getRadius());
   {
      setY(bottomEdge - getRadius());
      dy = dy * -1; 
   }

}
1

There are 1 answers

2
Glen Pierce On BEST ANSWER
if(getY() >= bottomEdge - getRadius()); <--remove this semicolon
{
      setY(bottomEdge - getRadius());
      dy = dy * -1; 
}

You have an extra semi colon. I recommend a coding style where you keep your open brackets on the same line as the if statements which they belong to.

if(something){
//code
}

not

if(something)
{
//code
}

I'm not sure that this alone will solve your problem since you appear to be setting the y value to be at the bottomEdge if it is ever greater than or equal to bottomEdge - getRadius(). So instead of bouncing off the edge, it just maintains that y value once you've hit the bottom edge.