[英]What's a good way to implement menus/scenes with SDL2 in C?
I'm making a game using SDL2.我正在使用 SDL2 制作游戏。 I was testing menus but a bug had me think I had to change my approach.
我正在测试菜单,但一个错误让我认为我必须改变我的方法。 I used to have a separate while loop for every menu, but now I'm trying to have a single loop for the whole game which handles different menus depending on the value of a variable (nested loops became a mess to handle).
我曾经为每个菜单设置一个单独的 while 循环,但现在我试图为整个游戏设置一个循环,它根据变量的值处理不同的菜单(嵌套循环变得一团糟)。 I thought about it for a while, but the variety of the needs of the menus gave me a lot of trouble.
想了想,但菜单需求的多样性给了我很大的麻烦。 If anyone can suggest me some good approach, here is what it requires:
如果有人可以建议我一些好的方法,这就是它所需要的:
Differentiated event handling (a menu should handle player movement keys, another some handle other things...);差异化事件处理(一个菜单应该处理玩家移动键,另一个处理其他事情......);
A way to free every variable declared with malloc() once a menu stops running;一种在菜单停止运行后释放使用 malloc() 声明的每个变量的方法;
An initialization that runs only once before each menu loop starts.在每个菜单循环开始之前只运行一次的初始化。
I hope someone can give me a good approach with pseudocode or just normal explaination, thanks in advance to those who'll help!我希望有人可以用伪代码或只是正常的解释给我一个好的方法,在此先感谢那些提供帮助的人!
You may want to consider doing the following:您可能需要考虑执行以下操作:
Every menu defines its own object of struct menu
, which contains at least the following three function pointers:每个菜单都定义了自己的
struct menu
对象,其中至少包含以下三个函数指针:
true
if the menu handles the input, or false
if it does not handle the input, because it is unrelated to the menu (for example if the input is a key for player movement).true
,如果不处理输入,则返回false
,因为它与菜单无关(例如,如果输入是玩家移动的键)。 Your program should have a pointer to a struct menu
which always specifies the currently active menu, or NULL
if no menu is active.你的程序应该有一个指向
struct menu
的指针,它总是指定当前活动的菜单,如果没有菜单是活动的,则为NULL
。 Whenever your program's main loop receives input, it calls the function pointer for the input function of the currently active menu.每当您的程序的主循环接收到输入时,它都会调用当前活动菜单的输入函数的函数指针。 If the menu's input function returns
true
, then the game's main loop will ignore the input, but if the menu's input function returns false
(for example if the input is a key for player movement), then the game's main loop will handle the input itself.如果菜单的输入函数返回
true
,那么游戏的主循环将忽略输入,但如果菜单的输入函数返回false
(例如,如果输入是玩家移动的键),那么游戏的主循环将自己处理输入.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.