Warm tip: This article is reproduced from serverfault.com, please click

graphics-使用C中的CSFML库进行跳转

(graphics - Make a jump with the CSFML library in C)

发布于 2020-12-03 07:56:02

对于一个项目,我必须跳一个精灵,但我不知道该怎么做,我已经对此进行了测试

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;

但是他不起作用,我的程序速度为60 fps,因此我希望跳转时间为1秒。Printf在这里查看恐龙的位置,但是我想跳跃是瞬间的,所以我没有时间看到跳跃。你有跳伞的想法吗?

Questioner
dav abs
Viewed
0
Erdal Küçük 2020-12-03 17:21:52

你的程序逻辑应如下所示:

注意:这仅是简化版本,而不是工作示例。它应该给你提示如何做。

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);
}