Search code examples
javagraphicsprojectbreakout

Breakout(Game Project) -Getting the ball to center the paddle -Java


My goal is getting the ball to be centered at the paddle even if the value of the ball radius were to change in future versions of the game. My only problem is implementing the correct math formula for the x coordinate of the gameball. I got the y coordinate formula working perfectly.

I do not need the correct answer. I just need guidance and suggestions to get the answer.

Here is a picture of the java program:

http://i33.photobucket.com/albums/d86/warnexus/ball.png

You can find the code below the comment "// Trouble figuring the math here".

    /** Radius of the ball in pixels */
private static final int BALL_RADIUS = 500;


private void setup_Paddle()
{
    // TODO Auto-generated method stub

    // x coordinate of the upper left corner
    // y coordinate of the upper left corner

    paddle = new GRect(20,20,PADDLE_WIDTH,PADDLE_HEIGHT);
    paddle.setFilled(true);
    paddle.setColor(Color.PINK);
    add(paddle,paddleInitialLocationX,paddleInitialLocationY);

}

private void setup_Ball()
{

    // Trouble figuring the math here
    int ballSetUpCoordX = (int) (paddle.getX());
    // Good Code!
    int ballSetUpCoordY = (int) (paddle.getY()-BALL_RADIUS);

    gameBall = new GOval(BALL_RADIUS,BALL_RADIUS);
    gameBall.setFilled(true);
    gameBall.setColor(Color.BLUE);

    add(gameBall,ballSetUpCoordX,ballSetUpCoordY);
}

    private GOval gameBall;
    private GRect paddle;
    private int paddleInitialLocationX = 200;
    private int paddleInitialLocationY = 500;

Solution

  • Coordinates are generally for the top left corner of an object. So to get any two objects o1 and o2 to be centered the same place, you have to offset based on size.

    Here we'll move o1's center to o2's center.

    int o2CenterX = o2.x - (o2.width/2);
    //If we just used o2CenterX, it would put the corner of o1 into the center of o2
    o1.x = o2CenterX - (o1.width/2);
    

    Repeat for y, which you appear to have already done(radius serves as width/2). You will likely have to adjust this formula slightly unless you want the paddle and ball intersecting on the screen.