Question

I am building a game using Sprite Kit and I want to gradually increase the difficulty (starting at 1.0) based on the time since starting the game.

Someone suggested that I should use a logarithmic calculation for this but I'm unsure how to implement this in Objective-C.

- (float)difficulty
{
  timeSinceStart = ???; // I don't what kind of object this should be to make it play nice w/ `log`
  return log(???);
}

Update #1

I know that I need to use the log method but I'm uncertain what values I need to pass to it.

Was it helpful?

Solution

Objective C is a superset of the C language, therefore you can use "math.h".

The function that computes the natural logarithm from "math.h" is double log(double x);

EDIT

Since you want the difficulty to increase as a function of time, you would pass the time as the argument to log(double x). How you would use that to calculate and change the "difficulty" is an entirely different question.

If you want to change the shape of the curve, either multiply the expression by a constant, as in 2*log(x) or multiply the parameter by a constant, as in log(2*x). You will have to look at the individual curves to see what will work best for your specific application.

OTHER TIPS

Since log(1.0) == 0 you probably want to do some scaling and translation. Use something like 1.0 + log(1.0 + c * time). At time zero this will give a difficulty of 1.0, and as time advances the difficulty will increase at a progressively slower pace whose rate is determined by c. Small values such as c = 0.01 will give a slow ramp-up, larger values will ramp-up faster.

@pjs gave a pretty clear answer. As to how to figure out the time: You probably want the amount of time spent actually playing, rather than elapsed time since launching the game.

So you will nee to track total time played, game after game.

I suggest you create an entry in NSUserDefaults. You can save and load double values to user defaults using the NSUserDefaults methods setDouble:forKey: and doubleForKey:

I would create an instance variable startPlayingTime, type double

When you start the game action running, capture the start time using

startPlayingTime = [NSDate timeIntervalSinceReferenceDate];

When the user passes the game/exits to the background, use

NSTimeInterval currentPlayTime =  [NSDate timeIntervalSinceReferenceDate] - startPlayingTime;

Then read the total time played from user defaults, add currentPlayTime to it, and save it back to user defaults.

You can then make your game difficulty based on

difficulty = log(1+ c * totalPlayTime);

(as explained by pjs, above) and pick some appropriate value for C.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top