Search code examples
cgraphicssfml

Make a jump with the CSFML library in C


For a project I have to make a sprite jumping and I don't know how to do I already tested this

while(sfRenderWindow_pollEvent(window, &event)) {
        if (event.type == sfEvtClosed) {
            sfRenderWindow_close(window);
        }

        if (event.type == sfEvtKeyPressed) {
            if (event.key.code == sfKeySpace || sfKeyUp)
                jumping = 1;
        }
    }

    if (jumping) {
        while (clock < 60) {
            printf("%f\n", dino_pos.y);
            if (clock < 30) {
                dino_pos.y -= 2;
                sfSprite_setPosition(dino, dino_pos);
                clock++;
            } else if (clock < 60) {
                dino_pos.y += 2;
                sfSprite_setPosition(dino, dino_pos);
                clock++;
            }
        }
        if (clock >= 60)
            clock = 0;
        
        printf("Jump\n");
    }
    jumping = 0;

But he doesn't work, my program is in 60 fps so I want that the jump is 1 second duration. Printf is here to view what the position of my dino but I guess that the jump was instant so I don't have the time to see the jump. Do you have idea for do a jump ?


Solution

  • Your program logic should look like this:

    Note: this is just a simplified version and not a working example. It should give you a hint how to do it.

    int main() 
    {
        openWindow();
        while (active) {
            getTime();
            processMessages();
            doLogic();
            renderScene();
            swapBuffers();
        }
        closeWindow();
    }
    
    void getTime()
    {
        // you have to know the time unit (sec, ms, us, ns, etc.)
        current_time = systemTime(); 
    }
    
    void processMessages()
    {
        while (nextEvent()) {
            if (EventType == EvtClosed) {
                active = false;
            }
            if ((EventType == KeyPressed) && (KeyType == KeySpace) && !jumping) {
                jump_start = current_time;
                jumping = true;
            }
        }
    }
    
    void doLogic()
    {
        if (jumping) {
            // time_frac has to be in range [0.0..1.0]
            time_frac = (current_time - jump_start) / time_units_per_second;
            // linear interpolation based on time fraction
            pos = start_pos * (1 - time_frac) + end_pos * time_frac;
        }
    }
    
    void renderScene()
    {
        printf("%f\n", pos);
    }