java, getting objects to bounce off walls

Discussion in 'Programmer's Corner' started by ninjaman, Feb 17, 2016.

  1. ninjaman

    Thread Starter Member

    May 18, 2013
    306
    1
    hello,

    been a while. hope your all doing well.
    i have some code in java, i have to make some balls bounce around a room. i can get them to bounce from the bottom and right hand sides but not the top and left hand sides.
    Code (Java):
    1.  
    2. /**
    3.      * Move this object according to its position and speed and redraw.
    4.      **/
    5.     public void move()
    6.     {        
    7.         // compute new position
    8.        yPosition += ySpeed;
    9.         xPosition += xSpeed;
    10.  
    11.         // check if it has hit the ground
    12.        if(yPosition >= (groundPosition - diameter) && ySpeed > 0) {
    13.             yPosition = groundPosition - diameter;
    14.             ySpeed = -ySpeed;
    15.         }
    16.    
    17.        if(xPosition >= (universe.getRightEdge() - diameter) && xSpeed > 0) {
    18.            xPosition = universe.getRightEdge() - diameter;
    19.            xSpeed = -xSpeed;
    20.         }
    21.         // draw again at new position
    22.         universe.draw(this);
    23.     }  
    24.  
    I am a little unsure about how this works. I have studied python and got on well with it but java is not clicking with me.

    any help or advice would be great!

    thanks
    simon
     
    Last edited by a moderator: Feb 18, 2016
  2. vpoko

    Member

    Jan 5, 2012
    258
    47
    You don't have any conditions to check for the left and top boundaries.

    How is the ball drawn, specifically what do its x and y coordinates represent? From the looks of it, I believe they represent the top-left corner of a bounding square around the ball (with the width and height of the square being the diameter of the ball). In that case, your extra two conditions would look like this (note that they're similar to the two conditions you have, but you don't offset for "diameter" since you want the ball to bounce from the left wall when the left side of the ball gets there, rather than when the right side gets there, and likewise you want it to bounce from the top when the top of the ball hits, not the bottom). Also, I'm assuming the top-left of your coordinate plane is (0, 0), as it would be in Java JFrame.

    Code (Text):
    1.  
    2. // check if it has hit the top edge
    3. if(yPosition <= 0 && ySpeed < 0) {
    4. yPosition = 0;
    5. ySpeed = -ySpeed;
    6. }
    7.  
    8. // check if it has hit the left edge
    9. if(xPosition <= 0 && xSpeed < 0) {
    10. xPosition = 0;
    11. xSpeed = -xSpeed;
    12. }
    13.  
     
  3. ninjaman

    Thread Starter Member

    May 18, 2013
    306
    1
    thanks for your help, got them bouncing around alot now. all the best

    simon
     
Loading...