Jump to content

How to properly restart gameloop/animation?


Go to solution Solved by kicken,

Recommended Posts

Hi all,

I adapted a "javascript game code" from tutorial https://spicyyoghurt.com/tutorials/html5-javascript-game-development/create-a-smooth-canvas-animation in my codepen : 

https://codepen.io/eaglehopes/pen/MWMgvjm

My problem was I could not properly restart the animation(i.e. gameloop) where it begins! I am using "R" key from keyboard to restart the amination, but every time I restart, not the positions but the initial velocities of the objects changes so code become undeterministic - changine each time with the same input. 

Can anybody say that where am I doing wrong again? 

Thanks.

Link to comment
Share on other sites

  • Solution

Set your old timestamp variable to null when the game is started/restarted.

this.oldTimeStamp = null;

Then in your game loop function, check if it's null and if so store the provided timestamp.

if (this.oldTimeStamp===null){
    this.oldTimeStamp=timeStamp;
}

This way your game always starts out at 0 for seconds passed.  Currently, your first iteration when the page loads is essentially random as it depends on how long it takes for the browser to run the first game loop after starting the page.

  • Thanks 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.