Search code examples
copenglpong

Opengl make "AI" paddle move up and down


I'm a bit of an openGL/programming noobie so I'm trying to make an "AI" for the right paddle. I know this isnt the proper way of doing it, what I SHOULD be doing is making it follow the ball. But right now I'm just trying to make it perpetually move up and down. I can't figure out how to do it, trying to use If loops like

if (paddle.pos[1] > 1){ paddle.pos[1] = paddle.pos[1] - delta}

I set delta to something like 0.01, 1 is the top of the screen. Obviously this isnt right because as soon as it goes down below 1 it goes up again, but I'm trying to do something like it.

2nd question - How do you move the ball from 0,0 when it starts? Kind of the same problem, am using if statements with the x values but thats definitely not right.

This is using C by the way.


Solution

  • Try something like this to make pos repeatedly go from 0 to 1 and back to 0:

    // Initialize.
    float pos = 0.0f;
    float delta = 0.01f;
    
    // On every update.
    pos += delta;
    if (pos > 1.0f) {
        pos = 1.0f;
        delta = -delta;
    } else if (pos < 0.0f) {
        pos = 0.0f;
        delta = -delta;
    }
    

    The key here is that you invert the sign of your increment each time you reach one of the end positions.