lundi 28 octobre 2019

Method that checks four edges of a ball one by one to see if it collided with a wall

Add a method to your code that checks each of the four edges of the ball one by one, checking if that edge has collided with the edge of the window. If so, it should change direction accordingly. For instance, if the ball was moving north-east (↗) and the top edge had hit the top of the screen, it would change the direction to south-east (↘) so that the ball would appear to bounce off the edge. (Remember that if the ball goes directly into a corner in a diagonal direction, two edges could hit at once, making it bounce straight back in the opposite diagonal direction.)

I am not sure how to get the four edges of an oval. I have the other 4 directions done (up, down, left, right) done but am not sure how to handle corners of the window.

public void move()
  {
   //direction right
   if(dir == 1)
   {
       int x = ball.getX();
       int y = ball.getY();
       ball.setLocation(x + 1,y);        
            if(x>425)
            {
                dir = 2;                           
            }
   }           
   //direction left
   if(dir == 2)
   {
       int x = ball.getX();
       int y = ball.getY();
       ball.setLocation(x - 1,y);          
            if(x<0)
            {
                dir = 1;
            }
   }           
   //direction down
   if(dir == 3)
   {
       int x = ball.getX();
       int y = ball.getY();
       ball.setLocation(x,y + 1);               
            if(y>425)
            {
                dir = 4;
            }
   }       
   //direction up
   if(dir == 4)
   {
       int x = ball.getX();
       int y = ball.getY();
       ball.setLocation(x ,y - 1);         
            if(y<0)
            {
                dir = 3;
            }
   }           
   //direction bottom right corner
   if(dir == 5)
   {
       int x = ball.getX();
       int y = ball.getY();
       ball.setLocation(x + 1,y + 1);                           
   }           
   //direction upper right corner
   if(dir == 6)
   {
       int x = ball.getX();
       int y = ball.getY();
       ball.setLocation(x + 1,y - 1);
   }       

   //direction bottom left corner
   if(dir == 7)
   {
       int x = ball.getX();
       int y = ball.getY();
       ball.setLocation(x - 1,y + 1);
   }       
   //direction upper left corner
   if(dir == 8)
   {
       int x = ball.getX();
       int y = ball.getY();
       ball.setLocation(x - 1,y - 1);      
   }
}

Finally, make sure to call this method whenever you move the ball. That way, after you move the ball 1 pixel in its current direction, you run the method to check if it has hit any edge, and change direction. At this point, your ball should move about the screen ricocheting as it goes.

Aucun commentaire:

Enregistrer un commentaire