필터 지우기
필터 지우기

How to make latch switch

조회 수: 5 (최근 30일)
Dirk te Brake
Dirk te Brake 2024년 2월 9일
댓글: Voss 2024년 2월 11일
Hi, i am making a animation but i want to be able to pause it when i press space and continue again when i press space (just like youtube). This is what i have but im not sure what to put in the while loop.
function myfun(~,event)
if event.Key == "space"
pause(0.1)
while event.Key ~= "space"
end
end
end
I feel like a simaler function needs to be inside the while loop but if i try that i get an error. Currently this function works as a press switch and not as a latch. And the pause doesnt work great either, once in a while it still continues a frame if i hold space. I'm not sure if the explanation is clear, so i attached the .m file.

채택된 답변

Voss
Voss 2024년 2월 10일
Try the attached m-file. See if it works as expected and makes sense.
  댓글 수: 8
Dirk te Brake
Dirk te Brake 2024년 2월 11일
Thank you for the clarification.
Voss
Voss 2024년 2월 11일
You're welcome! Let me know if you have any other questions.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2024년 2월 9일
You have the difficulty that the event field is not going to update as long as you are inside the KeyPressFcn handler.
You will have to do something along the lines of setting a control variable to indicate "go ahead", and then inside the keypress fnc handler, set the control variable to "pause" if it is currently "go ahead" and space is detected, but set it to "go ahead" if it is currently "pause" and space is detected. The control loop would look something like
while TheControlVariable == "pause"
pause(); %to give a chance for the KeyPressFcn handler to activate
end
  댓글 수: 1
Dirk te Brake
Dirk te Brake 2024년 2월 9일
The frequent use of "go ahead" confuses me, is it possible to explain it in a different way? This is what i came up with and it works but makes use of global variables.
global Action
Action = "";
% Within the animation loop
if Action == "space"
Action = "pause";
while Action ~= "space"
set(fig,'KeyPressFcn',@myfun);
pause(0.5)
end
Action = "Go ahead";
end
function myfun(~,event)
global Action
Action = event.Key;
end
I rather use something without global variables. So i made this, but it only works if you press any other key than 'space' the second time.
function myfun(~,event)
if event.Key == "space"
Action = 0;
while Action == 0
Action = waitforbuttonpress;
end
end
end
Do you have any idea's or tips on how to get rid of the global variable?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Maintain or Transition figure-Based Apps에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by