DEV Community

Noah11012
Noah11012

Posted on • Edited on

Using SDL: Pong 4

Our game is almost done. We have our Ball on the screen and it moves. But, the motion of the ball is only one dimensional. It can only move left or right but not take a diagonal trajectory.

I want to show a few preliminary changes that were made to the Ball class before moving on to the main changes.

First, the m_velocity member variable was renamed to m_velocity_x to better reflect the fact it is the velocity for the x-axis. Plus, for the y-axis, we have m_velocity_y. And finally, m_y for the position of the y-position.

private:
    int m_velocity_x;
    int m_velocity_y;
    double m_x;
    double m_y;
    ...
Enter fullscreen mode Exit fullscreen mode

Now for the main event.

All we really need to do is set a value for m_velocity_y. One option is to have a hard-coded value of an arbitrary value. Another and better way to do it is to have a random value created for the velocity.

void Ball::init(SDL_Renderer *renderer, int x, int y)
{
    ...
    std::uniform_int_distribution<> dist_y(1, 3);
    m_velocity_y = dist_y(rand_gen);

    if(dist_x(rand_gen) == 0)
    {
        m_velocity_y = -m_velocity_y;
    }
}
Enter fullscreen mode Exit fullscreen mode

We create a new std:uniform_int_distribution and we set the range between 1 and 3. But now the diagonals will only have a downward trend to them. To fix this, we randomize a value between 0 and 1. If it is a 0, we invert the velocity allowing it to travel in an upward trend. We'll reuse dist_x() since it already has the range from 0 to 1.

Before we compile and run, we have to change the Ball::update() method to reflect our changes:

void Ball::update(double delta_time)
{
    m_x = m_x + (m_velocity_x * delta_time);
    m_y = m_y + (m_velocity_y * delta_time);
    m_position.x = m_x;
    m_position.y = m_y;
}
Enter fullscreen mode Exit fullscreen mode

Compile and run.

What's next

For the next post, we'll get around to implementing collision detection for our paddles and the ball.

Github repository: https://github.com/Noah11012/sdl2-tutorial-code

Top comments (0)