Articles, Code and Video Tutorials for ARKit, Sprite Kit & SceneKit

How to Place Anchored Nodes Randomly In a Scene

Using ARKit and SpriteKit

Time for some fun with random numbers. Here’s a snippet of code passed down across generations of Swift developers: from grandfather to father, father to son….

Paste that into ANY of your Swift files, it doesn’t really matter which. Just do it outside of the class you’re pasting into. So let’s suppose you paste this into the Scene.swift file. Find the closing bracket at the very bottom of the file, and AFTER that bracket begin pasting the code above. Congrats, you’ve got a mighty useful extension of your Float class that takes in a minimum and maximum value and returns a random number between.

So let’s use it in our AR game. Below is the code to add an anchor to the scene (if you’re using the starting template, this appears in the touchesBegan statement of your Scene.swift file….

So what we’re doing here is randomizing the x and y placement of the anchor as well as the z placement (the distance from the user). Let’s look at just those lines, with some notes…

If you want to place an object randomly in front of or behind the user, this would work…