Methane
Methane is the main component of natural gas. It’s composed of one carbon atom and four hydrogen atoms, with the molecular formula CH4. This molecule is very easy to convert into a 3D model, with carbon in the middle and hydrogen evenly spaced around it, so jump right in!
Open up Molecules.swift and add the following function inside the Molecules
class, at the very end:
class func nodeWithAtom(atom: SCNGeometry, molecule: SCNNode, position: SCNVector3) -> SCNNode {
let node = SCNNode(geometry: atom)
node.position = position
molecule.addChildNode(node)
return node
}
All atoms added to a molecule follow a generic procedure, where they:
- Initialize a new node
- Are given a position
- Are added as a child to the molecule node
The previous function does just that and will be put to use for every atom of a molecule.
Next, replace your methaneMolecule
stub with the following:
class func methaneMolecule() -> SCNNode {
var methaneMolecule = SCNNode()
// 1 Carbon
let carbonNode1 = nodeWithAtom(Atoms.carbonAtom(), molecule: methaneMolecule, position: SCNVector3Make(0, 0, 0))
// 4 Hydrogen
let hydrogenNode1 = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(-4, 0, 0))
let hydrogenNode2 = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(+4, 0, 0))
let hydrogenNode3 = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(0, -4, 0))
let hydrogenNode4 = nodeWithAtom(Atoms.hydrogenAtom(), molecule: methaneMolecule, position: SCNVector3Make(0, +4, 0))
return methaneMolecule
}
It’s a large block of code, but still pretty straightforward. Here, you’re adding one carbon atom at the center of your molecule (0, 0, 0) and four hydrogen atoms around it (think north, east, south, west).
Build and run! Switch to the Methane segment to see the beginnings of your new molecule:
![BuildRun08](https://koenig-media.raywenderlich.com/uploads/2014/09/BuildRun08-281x500.png)
Awesome – now you’re rendering in style!
Where To Go From Here?
Here is the completed project with all of the code and resources for this Beginning Scene Kit tutorial. You can also find its repository on GitHub.
Congratulations, you’ve taken a great first step into Scene Kit and learnt the basics of this new and exciting 3D API!
So far, your atoms are in place but you still have to create bonds between them. You’ve also yet to experiment with COLLADA files and procedural geometry. So, what are you waiting for then?
If you want to learn more, check out iOS 8 by Tutorials. I go a bit further with this example there and show you how to implement the remaining molecules, and Jake Gundersen also has another entire chapter on more advanced Scene Kit techniques.
If you have any questions, comments or suggestions, feel free to join the discussion below!