Game Development Reference
In-Depth Information
Listing 15-9
.
Random Position Methods in the SharedConstants.swift File
func randomSign() -> Float {
if arc4random_uniform(2) == 0 {
return 1.0
}else {
return -1.0
}
}
func randomFloat() -> Float {
return Float(arc4random_uniform(100))
}
func randomPosition() -> SCNVector3 {
return SCNVector3Make(randomSign()*randomFloat(), 0.0,
randomSign()*randomFloat())
}
The first method you created,
randomSign()
, is a helper function to give you a negative or
positive number. You are using the
arc4random_uniform()
method, which is used to gen-
erate a random number between 0 and n-1. In the
randomSign()
method, you are asking
for a number between 0 and 1; then based on the number, you return a positive or negative
1 that will be used to change the sign for one of your axis points.
The next helper method is used to generate a number between 0 and 99. Again, you are
using the
arc4random
method and supplying it with the highest number you want to gen-
erate a random number. The extra item is a
Float
object that you will use in the next meth-
od.
The
randomPosition()
method is the main method that you will use in order create a ran-
dom position. You are setting the y-axis to 0.0 so that the items are all on the floor. As you
can see, it uses the two help methods in order to create an
SCNVector3
for any object you
want to place in the game scene.
The only thing left to do now is to update all your nodes to use this new method to place
the objects in random places. Now when you run the game, everything will be randomly
placed and make it that much more difficult and fun to find the enemy.
Summary