Jonny
Jonny

Reputation: 16298

Using arc4random_uniform with cocos2d-x

I was happy using arc4random_uniform since iOS, and also for iOS targets of cocos2d-x.

Turns out it doesn't work for Android. The error:

error: 'arc4random_uniform' was not declared in this scope

How can I get around this?

Worst case, at compile time I'd check if arc4random_uniform() exists, and if not, use some other method (like the old arc4random()...). I really would like to avoid using different code bases for different targets here.

Any other suggestions?

Note: As cocos2d-x is a "one code"→"many platforms", delegating this issue to Java code for Android would work against that.

Upvotes: 1

Views: 676

Answers (2)

Mauro Nonnis
Mauro Nonnis

Reputation: 262

Some of the C++ libs you can use in ios are not available in Android. Unfortunately arc4ramndom is just one of them.

So the only way is to use an alternative of the stdlib like std::rand() or the default random engine if you want something more. This is an example about how to use std::default_random_engine to get a random value in a given interval.

int randomValue(int from, int to) {

    std::random_device rd;
    std::default_random_engine e1(rd());
    std::uniform_int_distribution<int> uniform_dist(from, to);
    int mean = uniform_dist(e1);

    return mean;
}

Upvotes: 2

Ot&#225;vio Monteagudo
Ot&#225;vio Monteagudo

Reputation: 704

You can use Cocos2d native methods for generating random numbers. CCRANDOM_0_1() for example generates a random CGFloat between 0 and 1.

Upvotes: 1

Related Questions