如何用 C++ 和 Raylib 制作一个简单的菜单?

问题描述

我是一个新手程序员,我正在尝试使用 C++ 中的 Raylib 库。

但是我无法使用简单的开始菜单。我一直在尝试调用 void 函数,使用 switch 和简单的 if 语句...如何在 raylib 中使用 switch 或 if 语句制作一个简单的菜单而不关闭并打开程序的新窗口?我猜是在 While 循环中的某个地方?



#include "raylib.h"




int main(void)
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 800;
    const int screenHeight = 450;

    Initwindow(screenWidth,screenHeight,"raylib [core] example - basic window");

    SetTargetFPS(60);               // Set our game to run at 60 frames-per-second
    //--------------------------------------------------------------------------------------

    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {

       BeginDrawing();
        ClearBackground(RAYWHITE);
        DrawText("Congrats! You created your firstwindow!",190,200,50,LIGHTGRAY);
        EndDrawing();
        
        if(IsKeypressed(KEY_Q)) DrawText("New thing here",210,60,GREEN);
        if(IsKeypressed(KEY_W)) DrawText("New thing here number two",BLACK);

        

           
            
        }
        //----------------------------------------------------------------------------------
   
    CloseWindow();   
    return 0;


   }

我一直在尝试使用 Break、Pause 和 Goto 方法,如何在不关闭窗口的情况下结束 While 循环,是否需要更改 while 循环的语句?

解决方法

我不确定我是否理解您的问题...您想在不关闭窗口的情况下退出主游戏循环吗?这是不可能的,因为您将所有窗口内容都渲染在那里。对我来说,您似乎对语言本身缺乏一些基本的了解。 例如,您的 if 不会按照您想要的方式工作,因为它只会让文本闪烁一秒钟,而不是一直显示。

bool showText = false;

while(...) {
    if(IsKeyPressed(KEY_Q)) showText = !showText; // if you press Q again the text will 
    disappear

    if(showText) DrawText(...);
}

可能不是最干净的方式,但它有效。希望我的回答对你有帮助。 如果您不确定某事,您可以查看Raylib Examples

,

如果我理解正确的话,您需要在游戏启动前的菜单。您可以在同一个窗口中实现这一点,而无需尝试启动一个新窗口。

现在确切的解决方案将根据您制作的游戏类型而变化,但我能想到的最简单的解决方案是使用 if 语句来检查我们是否在 while 循环的菜单中。可能看起来像这样。

    bool isInMenu = true
    // Main game loop
    while (!WindowShouldClose())    // Detect window close button or ESC key
    {
        // Update here
        if(isInMenu)
        {
            if(IsKeyPressed(KEY_Q)) isInMenu = false;
        }
        else
        {
            if(IsKeyPressed(KEY_W)) isInMenu = true;
        }

        // Draw here
        BeginDrawing();
        if(isInMenu)
        {
            ClearBackground(RAYWHITE);
            DrawText("This is the menu",190,200,50,LIGHTGRAY);
        }
        else
        {
            ClearBackground(RAYWHITE);
            DrawText("Congrats! You created your firstwindow!",LIGHTGRAY);
        }
        
        EndDrawing();

    }
    //------------------------------------------------------------------------------