Jump to content

Having trouble syncing two different timers


Triplanetary
 Share

Recommended Posts

Hi there. My game has spaceships, and yesterday I implemented a button that allows the player to build a new spaceship. For testing purposes, I set the construction to take two seconds and set up a percentage that counts upward to 100%.

 

So I made two timers: one that fires in 2000 milliseconds and places the ship, and one that fires every 20 milliseconds to tick the construction progress up by 1%. These are both working fine except that I'm having trouble syncing them with each other. At first, I set the timer that places the ship at exactly 2000 ms, but I found that about half the time, the ship would be placed while the percentage was still in the 90s. I figured this was understandable; I think I read somewhere that you should assume about a 50 ms margin of error. So I set the timer to 2100 ms, which helped but didn't solve it, so I set it to 2200 ms, and the ship was consistently being placed after the percentage reached 100, with a noticeable but tolerable delay.

 

I thought I was good, until I tried the game again on my laptop. This laptop is very old with a 32-bit Pentium processor and only 1 GB of RAM, and I'm sure this accounts for the difference in timing, but the difference is way too severe. On the laptop, the ship consistently gets placed while the percentage is around 80! Can you please look at my code and tell me if there's a more robust way of setting up timers that doesn't vary so heavily based on hardware? Thanks!

var constructionPercentage = 0;this.newShipButton.text.setText('Under Construction: ' + constructionPercentage + '%');this.newShipButton.text.setStyle({fill: '#035069',font: 'normal 12px Arial'});this.time.events.repeat(20,100,incrementConstructionTimer,this);this.time.events.add(2200,instantiateShip,this);		function incrementConstructionTimer(){	constructionPercentage++;	this.newShipButton.text.setText('Under Construction: ' + constructionPercentage + '%');}
Link to comment
Share on other sites

Just in general you don't want to rely on two timers syncing up. You have two actions you want to happen that are directly related, you should treat it that way. So you should probably think about doing it this way...

 

timer function calls a function buildingShip and that function calls incrementConstructionTimer until it reaches 100% and then it fires instantiateShip.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...