/
Grid.swift
82 lines (65 loc) · 2.87 KB
/
Grid.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//
// Grid.swift
// NextReality_Tutorial4
//
// Created by Ambuj Punn on 5/2/18.
// Copyright © 2018 Ambuj Punn. All rights reserved.
//
import Foundation
import SceneKit
import ARKit
extension ARPlaneAnchor {
// Inches
var width: Float { return self.extent.x * 39.3701}
var length: Float { return self.extent.z * 39.3701}
}
class Grid : SCNNode {
var anchor: ARPlaneAnchor
var planeGeometry: SCNPlane!
var textGeometry: SCNText!
init(anchor: ARPlaneAnchor) {
self.anchor = anchor
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(anchor: ARPlaneAnchor) {
planeGeometry.width = CGFloat(anchor.extent.x);
planeGeometry.height = CGFloat(anchor.extent.z);
position = SCNVector3Make(anchor.center.x, 0, anchor.center.z);
let planeNode = self.childNodes.first!
planeNode.physicsBody = SCNPhysicsBody(type: .static, shape: SCNPhysicsShape(geometry: self.planeGeometry, options: nil))
if let textGeometry = self.childNode(withName: "textNode", recursively: true)?.geometry as? SCNText {
// Update text to new size
textGeometry.string = String(format: "%.1f\"", anchor.width) + " x " + String(format: "%.1f\"", anchor.length)
}
}
private func setup() {
planeGeometry = SCNPlane(width: CGFloat(anchor.width), height: CGFloat(anchor.length))
let material = SCNMaterial()
material.diffuse.contents = UIImage(named:"overlay_grid.png")
planeGeometry.materials = [material]
let planeNode = SCNNode(geometry: self.planeGeometry)
planeNode.physicsBody = SCNPhysicsBody(type: .static, shape: SCNPhysicsShape(geometry: planeGeometry, options: nil))
planeNode.physicsBody?.categoryBitMask = 2
planeNode.position = SCNVector3Make(anchor.center.x, 0, anchor.center.z);
planeNode.transform = SCNMatrix4MakeRotation(Float(-Double.pi / 2.0), 1.0, 0.0, 0.0);
// 1.
let textNodeMaterial = SCNMaterial()
textNodeMaterial.diffuse.contents = UIColor.black
// Set up text geometry
textGeometry = SCNText(string: String(format: "%.1f\"", anchor.width) + " x " + String(format: "%.1f\"", anchor.length), extrusionDepth: 1)
textGeometry.font = UIFont.systemFont(ofSize: 10)
textGeometry.materials = [textNodeMaterial]
// Integrate text node with text geometry
// 2.
let textNode = SCNNode(geometry: textGeometry)
textNode.name = "textNode"
textNode.position = SCNVector3Make(anchor.center.x, 0, anchor.center.z);
textNode.scale = SCNVector3Make(0.005, 0.005, 0.005)
addChildNode(textNode)
addChildNode(planeNode)
}
}