Question

I am new to sprite kit and am programming a simple game as a way to learn it.

My goal here is to get my sprite to move across the screen at random speeds. This sprite is spawned regularly, and the maximum speed that it can potentially go should increase with time in order to make the game more difficult.

To do this I am using the score, which is an integer based on time, to affect the minimum duration of movement of the sprite. The way I am trying to do this, as seen in the code below, still produces only integer values. I would love to have more granularity than just integers.

int rando = (arc4random() % 150) + 50;
int denom = _scores + 50;
float actualDuration = rando/denom + 1;
NSLog(@"%f", actualDuration);


SKAction * actionMove = [SKAction moveTo:CGPointMake(-_blimp.size.width/2, actualY) duration:actualDuration];

I started using floating variables in response to nielsbot's comment, and changed the structure of my code to reflect my changes, but I'm still getting only integer values and not decimals like I was looking for. Does anyone know why this is the case?

Resolved: I changed the integer variables to float variables before putting them in the calculation. Thanks for the help nielsbot!

Was it helpful?

Solution

float actualDuration = rando/denom + 1;
NSLog(@"%f", actualDuration);

I'm not 100% confident in the casting rules, but as far as I experienced it what happens is that rando and denom being integers and integer division is used, resulting in an integer value.

Therefore you need to cast at least the denominator to float but it's better to cast them both, as well as using the standard float notation for constant values (1.0f):

float actualDuration = (float)rando / (float)denom + 1.0f;
NSLog(@"%f", actualDuration);

Personally I tend to cast all integer values to float/double/CGFloat when using them in calculations just so that none of the casting rule issues can creep in.

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