How do I create a game update in a while loop

조회 수: 3 (최근 30일)
Lukas
Lukas 2025년 1월 17일
답변: Steven Lord 2025년 1월 17일
I have this project for class to make a game and for this game I wanted to add an update feature where every 1/30 seconds it completes a "tick." Basically running a while loop where it starts a timer at the begining, runs some functions, and then waits for the timer to hit 1/30 seconds before looping again to keep the game smooth. I've looked into the timer function but haven't been able to get it to work and I was hoping for some help.

답변 (1개)

Steven Lord
Steven Lord 2025년 1월 17일
numPasses = 0;
expectedDuration = seconds(1/30);
while numPasses < 5
dt = datetime('now');
n = 0;
while datetime('now')-dt < expectedDuration
drawnow
n = n + 1;
end
elapsed = datetime('now')-dt;
numPasses = numPasses + 1;
fprintf("Ended pass %d after 1/%1.6g seconds and %d executions of the loop body.\n", ...
numPasses, 1./seconds(elapsed), n)
fprintf("\tExpected time: %1.6g s\n\t Actual time: %1.6g s.\n", ...
seconds(expectedDuration), seconds(elapsed))
end
Ended pass 1 after 1/29.873 seconds and 484 executions of the loop body.
Expected time: 0.0333333 s Actual time: 0.033475 s.
Ended pass 2 after 1/29.8739 seconds and 980 executions of the loop body.
Expected time: 0.0333333 s Actual time: 0.033474 s.
Ended pass 3 after 1/29.873 seconds and 1033 executions of the loop body.
Expected time: 0.0333333 s Actual time: 0.033475 s.
Ended pass 4 after 1/29.8134 seconds and 804 executions of the loop body.
Expected time: 0.0333333 s Actual time: 0.033542 s.
Ended pass 5 after 1/29.7336 seconds and 1047 executions of the loop body.
Expected time: 0.0333333 s Actual time: 0.033632 s.
There is a bit of overhead from the datetime call in the while loop condition that may make this technique unsuitable for your (fairly quick) 1/30 second loop, but the expected versus actual times look pretty close.

카테고리

Help CenterFile Exchange에서 Board games에 대해 자세히 알아보기

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by