Togglebuttons need to be pressed multiple times?
Ältere Kommentare anzeigen
Basically right now this code should create a figure with two togglebuttons (ButtonQuit and ButtonUp). ButtonQuit should cause the figure to close and all calculations to end when toggled on and (for now) ButtonUp should display 'Pressed' when it is toggled on. Besides other possible glaring issues with my code I'd mainly like to fix an issue where it requires pressing the togglebuttons multiple times to continue with a task instead of pressing it just once.
clear all
GameOn = 1;
fig1 = figure('Color','k','Visible','on','Units','normalized','Position',[0 0.047 1 .863],'pointer','crosshair');
fig1 = get(gcf,'CurrentCharacter');
ButtonQuit = uicontrol('Style','togglebutton','String','Quit','Position',[1450 700 60 20],'Visible','on');
ButtonUp = uicontrol('Style','togglebutton','String','Up','Position', [1400 50 60 20],'Visible','on');
while GameOn == 1
set(ButtonUp,'Value',0)
waitforbuttonpress
if get(ButtonUp,'Value') == 1
msgbox('Pressed')
end
if get(ButtonQuit,'Value') == 1
GameOn = 0;
close all
msgbox('Game Over')
end
end
Antworten (1)
Geoff Hayes
am 13 Apr. 2020
Luke - consider using callbacks for your toggle buttons (can these be push buttons instead?). That way, you can remove the waitforbuttonpress call and just act on the button when its action occurs. The following code relies on the callbacks being nested in a main function and so this code should be saved to a file named myGameGui.m.
function myGameGui
close all
isGameOn = true;
hGameFigure = figure('Color','k','Visible','on','Units','normalized','Position',[0 0.047 1 .863],'pointer','crosshair');
currentCharacter = get(gcf,'CurrentCharacter');
hButtonQuit = uicontrol('Style','togglebutton','String','Quit','Position',[1450 700 60 20],'Visible','on', 'Callback', @QuitButtonCallback);
hButtonUp = uicontrol('Style','togglebutton','String','Up','Position',[1400 50 60 20],'Visible','on', 'Callback', @ButtonUpCallback);
while isGameOn
% add whatever game logic should be added here
% brief pause to allow callbacks to "interrupt" this tight loop
pause(0.01)
end
close(hGameFigure);
function QuitButtonCallback(~,~)
msgbox('Game Over');
isGameOn = false ;
end
function ButtonUpCallback(~,~)
msgbox('Pressed');
end
end
Kategorien
Mehr zu Just for fun finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!