Scene Kit Tutorial: Getting Started

Learn how to easily create 3D scenes in your iOS apps or games in this Scene Kit tutorial! By Ricardo Rendon Cepeda.

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 4 of this article. Click here to view the first page.

Atoms

Your box has been a fine star for the scene so far, and did its job in helping you create a pilot app, but now it’s time to kick it to the curb. Since you’re going to build an app with a purpose, you’re going to recast your actors and develop a 3D visualizer starring the common carbon compounds: natural gas, alcohol and Teflon.

These compounds will display as ball-and-stick models (molecules) made of bonded atoms. Atoms are quite complex, but for this tutorial a single sphere will represent each one as it’s an easy way to depict a basic unit of matter. This model is a simple, but useful way to represent molecular structures in chemistry, and you can learn more about it here.

The first atom you’ll create is, of course, carbon. Open up Atoms.swift and add the following class function inside the Atoms class:

class func carbonAtom() -> SCNGeometry {
  // 1
  let carbonAtom = SCNSphere(radius: 1.70)
    
  // 2
  carbonAtom.firstMaterial!.diffuse.contents = UIColor.darkGrayColor()
    
  // 3
  carbonAtom.firstMaterial!.specular.contents = UIColor.whiteColor()
    
  // 4
  return carbonAtom
}

Note: If you’re just getting to know Swift, a class function (otherwise, known as type function), is a function that is called directly on a class, rather than on an instance of that class.

In Objective-C, these methods are indicated by the use of plus sign before for the actual method name. For example: + (SCNGeometry *)carbonAtom;

Note: If you’re just getting to know Swift, a class function (otherwise, known as type function), is a function that is called directly on a class, rather than on an instance of that class.

In Objective-C, these methods are indicated by the use of plus sign before for the actual method name. For example: + (SCNGeometry *)carbonAtom;

This is a very compact function, but each line is worth understanding completely:

  1. As previously mentioned, atoms will be modeled as spheres. 1.70 is the van der Waals radius of carbon, which corresponds to the radius of an atom, in angstroms (10-10m), if it were a perfect sphere. Now that you’ve assigned a unit of measurement to your atom, the rest of your scene will be relative to this unit.
  2. firstMaterial is a property of type SCNMaterial, which defines your atom’s material. Think of diffused shading as the intrinsic/base color of a surface. In Scene Kit, you can define this by a color, texture, or other source. For additional information, please refer to How to Export Blender Models to OpenGL ES: Part 2/3
  3. Specular shading is another material property, which is the reflective color of a surface. For most materials, this is usually pure white.
  4. All atom models in this tutorial will be declared as type methods, following a factory method pattern. This will be especially useful when creating molecules with many different atoms of the same type, with these methods returning a fully modeled geometry object.

Now that you understand how to create a type method for a carbon atom, the rest of the atoms in this tutorial will be just as easy to model. Add the following code to the Atoms class:

class func hydrogenAtom() -> SCNGeometry {
  let hydrogenAtom = SCNSphere(radius: 1.20)
  hydrogenAtom.firstMaterial!.diffuse.contents = UIColor.lightGrayColor()
  hydrogenAtom.firstMaterial!.specular.contents = UIColor.whiteColor()
  return hydrogenAtom
}
  
class func oxygenAtom() -> SCNGeometry {
  let oxygenAtom = SCNSphere(radius: 1.52)
  oxygenAtom.firstMaterial!.diffuse.contents = UIColor.redColor()
  oxygenAtom.firstMaterial!.specular.contents = UIColor.whiteColor()
  return oxygenAtom
}
  
class func fluorineAtom() -> SCNGeometry {
  let fluorineAtom = SCNSphere(radius: 1.47)
  fluorineAtom.firstMaterial!.diffuse.contents = UIColor.yellowColor()
  fluorineAtom.firstMaterial!.specular.contents = UIColor.whiteColor()
  return fluorineAtom
}

There you have it: hydrogen, oxygen, and fluorine.

All atoms have the same method template and simply differ in sphere radius and diffuse color. In order to display all these atoms together, you’ll add them to a single node. To do so, add the following type method to the Atoms class, at the bottom of the file (just before the closing brace):

class func allAtoms() -> SCNNode {
  let atomsNode = SCNNode()
    
  let carbonNode = SCNNode(geometry: carbonAtom())
  carbonNode.position = SCNVector3Make(-6, 0, 0)
  atomsNode.addChildNode(carbonNode)
    
  let hydrogenNode = SCNNode(geometry: hydrogenAtom())
  hydrogenNode.position = SCNVector3Make(-2, 0, 0)
  atomsNode.addChildNode(hydrogenNode)
    
  let oxygenNode = SCNNode(geometry: oxygenAtom())
  oxygenNode.position = SCNVector3Make(+2, 0, 0)
  atomsNode.addChildNode(oxygenNode)
    
  let fluorineNode = SCNNode(geometry: fluorineAtom())
  fluorineNode.position = SCNVector3Make(+6, 0, 0)
  atomsNode.addChildNode(fluorineNode)
    
  return atomsNode
}

This is a rather lengthy function, but it’s also easy to digest. It simply creates and returns a new node that contains four children, one for each atom, nicely positioned along the x-axis. To see them in your scene, open up ViewController.swift and add the following lines to viewDidAppear(animated:), just below the call to sceneSetup:

geometryLabel.text = "Atoms\n"
geometryNode = Atoms.allAtoms()
sceneView.scene!.rootNode.addChildNode(geometryNode)

Finally, remove your previous box object by deleting these lines from inside sceneSetup:

let boxGeometry = SCNBox(width: 10.0, height: 10.0, length: 10.0, chamferRadius: 1.0)
let boxNode = SCNNode(geometry: boxGeometry)
scene.rootNode.addChildNode(boxNode)
geometryNode = boxNode

Build and run (or, as Radioactive Man would say: “Up and atom!”). You should see four nicely rendered atoms:

BuildRun07

Awesome job so far! The scene is coming together, and now is a good time to take a quick break if you need to.

Molecules

As you may remember from science class, molecules are groups of two or more atoms held together by chemical bonds. All carbon compounds comprise of molecules of varying complexity. In this section of the tutorial, you’ll build 3D models for various molecules, using your new atoms as building blocks.

You’ll learn about and build each molecule separately, but they’ll all follow a similar pattern. Your first task is to lay the foundation of your molecules, so open up Molecules.swift and add the following lines inside the Molecules class:

class func methaneMolecule() -> SCNNode {
  var methaneMolecule = SCNNode()
  return methaneMolecule
}
class func ethanolMolecule() -> SCNNode {
  var ethanolMolecule = SCNNode()
  return ethanolMolecule
}
  
class func ptfeMolecule() -> SCNNode {
  var ptfeMolecule = SCNNode()
  return ptfeMolecule
}

Just like your atoms, you develop your molecules as type methods, which return nodes that you can plug directly into your scene.

Next, open up ViewController.swift and add the following lines inside segmentValueChanged(sender:):

// 1
geometryNode.removeFromParentNode()
currentAngle = 0.0
    
// 2
switch sender.selectedSegmentIndex {
case 0:
  geometryLabel.text = "Atoms\n"
  geometryNode = Atoms.allAtoms()
case 1:
  geometryLabel.text = "Methane\n(Natural Gas)"
  geometryNode = Molecules.methaneMolecule()
case 2:
  geometryLabel.text = "Ethanol\n(Alcohol)"
  geometryNode = Molecules.ethanolMolecule()
case 3:
  geometryLabel.text = "Polytetrafluoroethylene\n(Teflon)"
  geometryNode = Molecules.ptfeMolecule()
default:
  break
}
    
// 3
sceneView.scene!.rootNode.addChildNode(geometryNode)

Here’s the breakdown for the code:

  1. Whenever you select a new segment, your scene changes to display a new model. To clean up the previous model, it must be removed from its parent node (i.e. the scene’s root node) and have its rotation angle reset.
  2. A new model is assigned to geometryNode, and geometryLabel is updated accordingly with the model’s name.
  3. Finally, the new model is added to the scene.

Build and run! Try selecting different segments, and you’ll notice an empty scene for Methane, Ethanol and PTFE, since you haven’t created the molecules yet. Make sure the label’s text changes for each segment. Also, note that Atoms will always display with its default starting position upon selection.

Ricardo Rendon Cepeda

Contributors

Ricardo Rendon Cepeda

Author

Over 300 content creators. Join our team.