Can someone tell me how to properly write
arc4random() %#;
to include not only positive numbers but negative numbers as well? I'm trying to have an image (SKSpriteNode from Sprite Kit) be able to randomly move in any direction within a 2D environment.
arc4random()
return type is anu_int32_t
which is anunsigned int
so it can't directly return a negative number.You will need to 'manipulate' it in order to receive a positive or negative range.
First, I would like to suggest to use
arc4random_uniform()
instead ofarc4random() %
since it avoids "modulo bias" when the upper bound is not a power of two.As for your question, you can do the following by subtracting the wanted range.
For Example:
Will give values between 0 and 99,
But by subtracting 50 like this:
We will now get a random value between -50 and 49;
EDIT- If you assign the results to a variable, I think you will need to type cast the
arc4random_uniform
result to avoid compiler warning, although I am not sure if necessary.So it would look like this: