How do I create a game update in a while loop
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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.
0 comentarios
Respuestas (1)
Steven Lord
el 17 de En. de 2025
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
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.
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!