java, getting objects to bounce off walls

Thread Starter

ninjaman

Joined May 18, 2013
341
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.
Java:
/**
     * Move this object according to its position and speed and redraw.
     **/
    public void move()
    {         
        // compute new position
       yPosition += ySpeed;
        xPosition += xSpeed;

        // check if it has hit the ground
       if(yPosition >= (groundPosition - diameter) && ySpeed > 0) {
            yPosition = groundPosition - diameter;
            ySpeed = -ySpeed;
        }
   
       if(xPosition >= (universe.getRightEdge() - diameter) && xSpeed > 0) {
           xPosition = universe.getRightEdge() - diameter;
           xSpeed = -xSpeed;
        }
        // draw again at new position
        universe.draw(this);
    }
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:

vpoko

Joined Jan 5, 2012
267
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:
// check if it has hit the top edge
if(yPosition <= 0 && ySpeed < 0) {
yPosition = 0;
ySpeed = -ySpeed;
}

// check if it has hit the left edge
if(xPosition <= 0 && xSpeed < 0) {
xPosition = 0;
xSpeed = -xSpeed;
}
 
Top