Press ESC to close

Changing the angle of the Node with ARKit

Hello friends, in this article, we will talk about how to translate the Node we created with Swift ARKit. We will do this example on the house project we created earlier. You can find that article here.

As we did in previous projects, we first add the node that creates the house to our scene. Then we need to change the Euler Angle of this house. More information about the Euler angle can be found here. Of course, we cannot give a value in degrees to this angle. So we need to convert degrees to radians. For this we write a variable to Int. Then we can change the angle of the Node with this variable.

//
//  ViewController.swift
//  arkit-rotation
//
//  Created by Omer Sezer on 5.07.2021.
//

import UIKit
import ARKit

class ViewController: UIViewController {

    @IBOutlet weak var sceneView: ARSCNView!
    let configuration = ARWorldTrackingConfiguration()
        
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
    }
 
    func setUI() {
        // MARK: sceneView
        sceneView.debugOptions = [.showFeaturePoints, .showWorldOrigin]
        sceneView.session.run(configuration)
        sceneView.autoenablesDefaultLighting = true
        
        setHomeNode()
    }
    
    func setHomeNode() {
        let nodeRoof = SCNNode(geometry: SCNPyramid(width: 0.1, height: 0.1, length: 0.1))
        nodeRoof.geometry?.firstMaterial?.diffuse.contents = UIColor.red
        nodeRoof.eulerAngles = SCNVector3(0, 0, 90.degreesToRadians)
        
        let nodeHome = SCNNode(geometry: SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0))
        nodeHome.geometry?.firstMaterial?.diffuse.contents = UIColor.blue
        
        let nodeDoor = SCNNode(geometry: SCNPlane(width: 0.03, height: 0.06))
        nodeDoor.geometry?.firstMaterial?.diffuse.contents = UIColor.green
        
        nodeRoof.position = SCNVector3(-0.1, 0.1, -0.7)
        nodeHome.position = SCNVector3(0, -0.05, 0)
        nodeDoor.position = SCNVector3(0, -0.02, 0.05)
        
        sceneView.scene.rootNode.addChildNode(nodeRoof)
        nodeRoof.addChildNode(nodeHome)
        nodeHome.addChildNode(nodeDoor)
    }
}

extension Int {
    var degreesToRadians: Double { return Double(self) * .pi / 180}
}

Actually, it’s that easy. You can access the project here. If you have questions, you can reach us by sending an e-mail or comment. Good work.

Leave a Reply

Your email address will not be published. Required fields are marked *