I'm making my first game in, Pong, and I'm trying to make the ball's Y increase or decrease, depending on where it impacts the paddle. After implementing the code below, the ball only goes down, but not up. What could the problem be?

    //30px on either side of the actual center of the paddle is considered the center
    if((ball.getY() > ((paddle.getH() / 2) + 30)))
        ball.setY(ball.getY() + 10);
    else if ((ball.getY() < ((paddle.getH() /2) - 30)))
        ball.setY(ball.getY() - 10);
  • 1
    \$\begingroup\$ You have too many magic constants. Start factoring out your numbers (eg. 30, 10) into variables so they make sense. It's hard to tell what exactly is going on. Also, wrap the if statements in brackets, eg. if (...) { ... } \$\endgroup\$
    – ashes999
    Feb 20, 2012 at 17:30
  • \$\begingroup\$ I have made pong game with your desired effect, see github.com/matejkramny/Pong/blob/master/src/pong/Ball.java starting on line 22 \$\endgroup\$
    – code ninja
    Oct 6, 2012 at 14:30

2 Answers 2


I think the center calculation is off as its not taking into account the position of the paddle at all.

Shouldn't it be something like (posY + (height / 2) +/- fudgeFactor) or the like?

Depending on where 0,0 is on the y axis this could cause one of the if's to always return true as it is comparing against a location based off of the paddle always being at the 0 y location.


Your ball should have direction vector (i,j). Your pad can have vector field. Let's say your pads are vertical (since you haven't mentioned are they vert or horiz).

Vector field for a pad should be something like:
for the upper corner: (0, 1) 1 is y-up
for middle of pad: (1, 0)
for bottom corner: (0, -1)

everything in between are interpolated values. (these values can be easily calculated when needed using with/height etc).

Next thing you do, is do addition of vector from vector field and ball direction field (but you need to * -1 i value of dir vector because ball changes X direction).

So if input (ball direction) vector is (-1, -1) that is 225 degrees, and ball hits almost to bottom corner on left pad vector from vector field would be (0.1, -0.9). Invert ball dir vect i value and perform addition; that is (1, -1) + (0.1, -0.9) and resulting vector is (1.1, -1.9), and you can convert this to angles and work your way from there. Also good thing would be to normalize this vector before giving it to ball.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .