Wednesday, February 18, 2009

Timer Tutorial

*This tutorial is taken with permission from user A_Nub at MforMature.net


Well, I am not sure how many people have trouble with this, but hey it is always good to have a reference. This is the second tutorial I have written so bear with me if and when I explain things poorly.

Prerequisite:
* Understanding of C/C++ syntax
* Comfortable Coding in C/C++

Concepts Covered:
* Timing (based on ctime)


Intro:
Ok so lets start with an example. Say you have a variable, and you need it to be updated exactly every 2 seconds. How would you achieve this? Well you could use a loop and stall it the proper amount of time for the CPUs speed to wait 2 seconds. That however would be silly and uncalled for, and wastes CPU time for other processing. So we will use a simple utility found in the standard C library called ctime (time.h).

The Process:
time.h contains many useful functions for time, including but not limited to obtaining the date, the time of day and number of ticks.

Tick - a single iteration of the never ending "loop" on the RTC (Real Time Clock) processor. A ticks interval is always exactly the same time from the previous tick. There is a constant that defines this time, and is relevant to the device being compiled for.

What we are using:
Now we will move into ctime and how we will obtain the time passed by using a simple calculation via ticks. Now you may ask, "if we can just get the time, why waste cpu calculating the time?" this is because obtaining the systems time is actually a lot slower and requires more memory.

So we will need only 2 things from ctime.

1) clock_t clock(); // returns the current tick
2) CLOCKS_PER_SEC;

Now we have introduced some questions. "What is a clock_t?" and "What is CLOCKS_PER_SEC?"
A clock_t is simply a typedef unsigned int.
CLOCKS_PER_SEC is simply the number of ticks per second.

The TUT:
Ok here we go. First off we need to create some variables.

/*
Timer.cpp By: Zachry Thayer (c) 2009
*/

#include

class Timer{
private:
clock_t startTick;//the tick for when we first create an instance
clock_t currTick;//the most recent tick read
clock_t lastTick;//the tick from the last update
clock_t deltaTick;//currTick - lastTick

float elapsedSeconds;// time since created in seconds
float deltaSeconds;// time since last tick in seconds
/*


Now we need to declare our class methods

/*
Constructor
*/
Timer();

/*
Deconstructor
*/
~Timer();

/*
Update Timer (to be called once per main loop[more often for more accuracy])
*/
void update();

/*
Return Elapsed time since the timer was created
*/
float elapsedTime();

/*
Return Delta time since the timer was created
*/
float deltaTime();

/*
Reset elapsed time to 0
*/
void reset();
};


Seems simple enough so far, now we get into the actual code.

/*
Constructor
*/
Timer::Timer(){
startTick = clock();//Obtain current tick
currTick = startTick;//All ticks are the same since we have just been created
lastTick = currTick;//copy ^
deltaTick = 0;// X - X = 0

elapsedSeconds = 0.f;//no time has passed
deltaSeconds = 0.f;//ditto ^
}

/*
Deconstructor
*/
Timer::~Timer(){
//we did not allocate any dynamic data
}


Ok simple enough so far, just initializing variables. Now for the part you all wanted the timer update.


/*
Update Timer (to be called once per main loop[more often for more accuracy])
*/
void Timer::update(){
lastTick = currTick;//store the currTick before we update it
currTick = clock();//update current tick
deltaTick = currTick - lastTick;//calculate the difference in ticks
deltaSeconds = (float)deltaTick/(float)CLOCKS_PER_SEC;//Simple division to calculate seconds based on the number of ticks
elapsedSeconds += deltaSeconds;// add to overall time
}


Pretty Simple huh.
The rest here is self explanatory.

/*
Return Elapsed time since the timer was created
*/
float Timer::elapsedTime(){
return elapsedSeconds;
}

/*
Return Delta time since the timer was created
*/
float Timer::deltaTime(){
return deltaSeconds;
}

/*
Reset elapsed time to 0
*/
void reset(){
elapsedTime = 0.f;
}



Original Tutorial Link

Adding Background Music to an Application

I was stuck until very recently working on a game for the iPhone because I wasn't sure how to setup a loop of music that would act in the background.

It's quite simple to do and I based it myself off of what Chris Roper, from [URL="http://iphonedevtips.blogspot.com/2009/01/avfoundation-and-audio.html"]iPhoneDevTips[/URL], does in his article but it is slightly modified to work in the App Delegate's "applicationDidFinishLaunching."

- (void)applicationDidFinishLaunching:(UIApplication *)application /* this is where you can place code for beginning as soon as the application launches, as indicated by the section name */
{

// Override point for customization after app launch
[window addSubview:viewController.view]; /* adding my main view to the view controller */
[window makeKeyAndVisible]; //


AVAudioPlayer *myExampleSound; /* this variable can be named differently - This line is subclassing AVAudioPlayer */

NSString *myExamplePath = [[NSBundle mainBundle] pathForResource:@"*Music filename*" ofType:@"mp3"]; /* *Music filename* is the name of the file that you want to play. BE SURE that you type the correct characters as the system is case-sensitive. It caused a crash for me... Very painful. */

myExampleSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:myExamplePath] error:nil]; // this is setting a path so that the content can be loaded.

myExampleSound.delegate = self;

[myExampleSound play];
//[myExampleSound stop];

[myExampleSound prepareToPlay];

myExampleSound.numberOfLoops = 10; /* can be as many times as needed by the application */

}


You can insert this in quite a few general places. MAKE SURE to #import the AudioToolBox framework and AVFoundation framework into your main header file in order to not have problems during the build/compile process.

---------------------------------------------------------------------------------------------------------------

Leave comments below if you see any issues with the code or have questions about it.

Hello World!

No, this isn't a tutorial for writing a Hello World application for iPhone. Hey. You might know me from consumer electronics sites and whatnot. I'm known as Spike. I began programming exclusively for the iPhone and iPod Touch roughly a month and a half ago. I'm a very new beginner and know how it feels to be told, "Go reread the docs." My goal for this blog is to teach by showing heavily explained code snippets, but still leaving you the chance to figure out how/where/when/why to use it.

I won't post as often as other iPhone development communities, but I hope that you will find my posts educational.

As with any tutoral, please leave comments asking for help if needed, or for making suggestions.

Thanks