Ahot's weblog

Monday Sep 10, 2007

During two-games developing I have found one useful solution.
It's nested-clocks - simple java-class for managing of time-threads.
Main idea is that if you pause clock then all children clocks will be paused too.
public class GameClock {
	
	private boolean paused = true;
	private long startedTime = 0;
	private long pausedTime = 0;
	private GameClock parentClock;
	//create top-clock, without parent
	public GameClock() {
	}
	//create nested-clock
	public GameClock(GameClock parentClock) {
		this.parentClock=parentClock;
	}
	//just for comfort, easy way to get time in parent clock
	private long getParentTime() {
		if (parentClock==null) return System.currentTimeMillis();
		return parentClock.getTime();
	}
	//getting current time
	public long getTime() {
		return (paused?pausedTime:getParentTime()) - startedTime;
	}
	//setting current time to zero, and starting clock
	public void start() {
		paused = false;
		startedTime = getParentTime();
	}
	//pause current time
	public void pause() {
		if (!paused) {
			paused = true;
			pausedTime = getParentTime();
		}
	}
	//resume current time
	public void resume() {
		if (startedTime==0) start();
		if (paused) {
			paused = false;
			startedTime += getParentTime() - pausedTime;
		}
	}
	//sleep in current thread, using non-system time but this-clock time
	public void sleep(long mlsec) {
		long now=getTime();
		while(getTime()-now<mlsec) {
			try {Thread.sleep(mlsec - (getTime()-now));}catch(Exception e) {return;}
			if ((getTime()-now)<0) return;
		}
	}
}
Comments:

One question: what do you use nested-clock for? Is a single clock not enough for the whole game?

Posted by Sila Kayo on September 10, 2007 at 03:37 PM GMT+03:00 #

It's just experiment. Anyway "System.currentTimeMillis()" does all :).

Look at shiftIt game for example.
There are timers here:
- level timer (level finishes after N second)
- step timer (you should find combination with M seconds)
- animation timer (items should be moved with speed K, when items is moving level and step timers should be paused)
- global timer (game should be paused, when we go to main menu)

So hierarchy of clocks may looks so:

[1] Global
[1.1] level
[1.1.1] step
[1.2] animation

Using:
when we resume game: Global.resume(); (all nested timers resume too automaticaly)
when we pause game: Global.pause();(all nested timers pause too automaticaly)
when we animate falling of items: animation.resume(); level.pause();
and so on...

Posted by ahot on September 10, 2007 at 04:30 PM GMT+03:00 #

Ok, now I understand :)
Thanks for explaining.

Posted by Sila Kayo on September 10, 2007 at 04:44 PM GMT+03:00 #

Post a Comment:
  • HTML Syntax: NOT allowed

FEEDS:

BOOKMARKS:

This blog copyright 2009 by ahot