0

https://github.com/H1Tech/Pong/tree/master/Pong/src/game

The above is the entire source of the current version of the game.

private void ballColide() {
    int diameter = Pong.pong.ball.getDiameter();
    int ballX = Pong.pong.ball.getX() - diameter;
    int ballY = Pong.pong.ball.getY() - diameter;
    double relInt = (y+(height/2)-ballY);
    double normInt = (relInt/(height/2));
    double angle = normInt * Pong.pong.ball.MAX_ANGLE;
    long velX = Math.round(Pong.pong.ball.SPEED*Math.cos(angle));
    long velY = Math.round(Pong.pong.ball.SPEED*Math.sin(angle));
    if(paddleNum == 1){
        if(ballX - Pong.pong.ball.velX <= x+width/2 && ballX - Pong.pong.ball.velX >= 0){
            if(ballY <= y+height/2 && ballY >= y-height/2){
            Pong.pong.ball.setVel(velX, velY);
            }
        }
    }
    if(paddleNum == 2){
        if(ballX + diameter + Pong.pong.ball.velX >= x-width/2 && ballX + diameter + Pong.pong.ball.velX <= Pong.pong.width){
            if(ballY <= y+height/2 && ballY >= y-height/2){
                Pong.pong.ball.setVel(velX, velY);
            }
        }
    }   
}

The code above is the current collision detection system.

My problem is that sometimes the ball phases through the paddle, and other times the ball gyrates on the paddle.

I would very much appreciate tips on how to fix this.

Please keep in mind that I am a pre-college student (Starting this fall). I just opened what we are supposed to be learning (JFrames without libraries). Most likley this code is unorthodox or against common standards. If you have the time, would you mind telling me what I got wrong/right or otherwise. I appreciate your time.

Tyler Fricks
  • 91
  • 1
  • 8
  • Swing has a nice (if basic) `Shape` API which does a lot of this work for you, for example, you could simply create a `Rectangle` of the paddle and the ball and simply check to see if they `intersect`...much simpler – MadProgrammer Jul 22 '15 at 04:05
  • 1
    Your issue is that you're only setting ball velocity. You should also set its position in an intersection. Set it to a pixel in front of the paddle. Right now on a collision the ball may be inside the paddle, then is detected. You update the velocity but the ball is still inside the paddle. Next frame the ball moves but is still just inside the paddle. This then repeats. – David M Jul 22 '15 at 04:10
  • Here's a [complete example](http://stackoverflow.com/a/14001011/230513) and possible [duplicate](http://stackoverflow.com/q/13999506/230513). – trashgod Jul 22 '15 at 04:11
  • 1) See [Collision detection with complex shapes](http://stackoverflow.com/a/14575043/418556) for a working example. 2) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson Jul 22 '15 at 09:29

0 Answers0