Nested Model Matrices (Metal Part 12)
Using the parent transform to calculate the child model matrix, taking into account the transformation applied to the parent.
Source Code
References
Table of Content
Implementation
The model matrix is now located in the transform level, and every lateUpdate, the transform updates its model matrix.
Each transform will check if it has a parent, and will multiply the parent model matrix by its model matrix, making a new model matrix that takes into account the transformations of the parent.
1class Transform { 2 ... 3 4 public var modelMatrix: float4x4 = matrix_identity_float4x4 5 6 private var _parent: Transform? 7 public var parent: Transform? { 8 return _parent 9 } 10 11 public func setParent(_ parent: Transform){ 12 _parent = parent 13 } 14 15 private func updateModelMatrix() { 16 var result: float4x4 = matrix_identity_float4x4 17 18 result.translate(position: position) 19 result.scale(scale: scale) 20 21 result.rotateX(angle: rotation.x) 22 result.rotateY(angle: rotation.y) 23 result.rotateZ(angle: rotation.z) 24 25 if(_parent != nil){ 26 modelMatrix = _parent!.modelMatrix * result 27 } else { 28 modelMatrix = result 29 } 30 } 31 32 // https://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html 33 // LateUpdate is called after all Update functions have been called 34 public func lateUpdate(){ 35 if let updatableSelf = self as? LateUpdatable { 36 updatableSelf.doLateUpdate() 37 } 38 39 updateModelMatrix() 40 41 for child in _children { 42 child.lateUpdate() 43 } 44 } 45}
Result
Now the cube moves along the parent quad.