This is my try on a pong.
It was finished a while ago.
I started small and simple but things got pretty ugly pretty fast.
I had a few months break from programing because of some obligations... and to get back into shape I decided to make a pong clone, I got carried away and before I knew the source got big and I didn't want to break it into separate files. :/
Video: Source: https://github.com/Godsend72/GitFolderMy AI code looks like this:
I have a prediction ball that travels 1.3 times faster than the real ball.
AI paddle moves only when the ball is on his side of the screen.
When the ball collides with the player paddle I set it to the same position as the real ball.
AI prediction example:
AI logic:
if (predBall.getGlobalBounds().left > 0 && predBall.getGlobalBounds().left + predBall.getGlobalBounds().width + 25.f < screenWidth)
{
predBall.move(predBallVel.x * deltaTime.asSeconds() * 1.3f, predBallVel.y * deltaTime.asSeconds() * 1.3f);
}
if (ball.getPosition().x >= screenWidth / 2.f)
{
if (rightBat.getGlobalBounds().top + rightBat.getGlobalBounds().height / 2.f < predBall.getPosition().y && !rightBat.getGlobalBounds().intersects(predBall.getGlobalBounds()))
{
rightBat.move(0, paddleSpeed * deltaTime.asSeconds());
if (rightBat.getGlobalBounds().top + rightBat.getGlobalBounds().height >= screenHeight)
rightBat.move(0, -paddleSpeed * deltaTime.asSeconds());
}
else if (rightBat.getGlobalBounds().top + rightBat.getGlobalBounds().height / 2.f > predBall.getPosition().y && !rightBat.getGlobalBounds().intersects(predBall.getGlobalBounds()))
{
rightBat.move(0, -botPaddleSpeed * deltaTime.asSeconds());
if (rightBat.getGlobalBounds().top <= 0)
rightBat.move(0, botPaddleSpeed * deltaTime.asSeconds());
}
}