Skip to content

Instantly share code, notes, and snippets.

@MasDennis
Created April 2, 2021 13:48
Show Gist options
  • Save MasDennis/66cd4ca3c7447924cfa2cc2cb0f777aa to your computer and use it in GitHub Desktop.
Save MasDennis/66cd4ca3c7447924cfa2cc2cb0f777aa to your computer and use it in GitHub Desktop.
//
// LoopAndGestureViewController.swift
//
//
// Created by Dennis Ippel on 02/04/2021.
//
import UIKit
import RealityKit
import Combine
class LoopAndGestureViewController: UIViewController {
var arView: ARView!
var animUpdateSubscription: Cancellable?
var cubeMaterial: SimpleMaterial!
var cubeEntity: ModelEntity!
override func viewDidLoad() {
super.viewDidLoad()
arView = ARView(frame: view.frame,
cameraMode: .nonAR,
automaticallyConfigureSession: false)
view.addSubview(arView)
let skyboxResource = try! EnvironmentResource.load(named: "decor_shop_2k")
arView.environment.lighting.resource = skyboxResource
arView.environment.background = .skybox(skyboxResource)
let cubeMaterial = SimpleMaterial(color: .blue, isMetallic: true)
cubeEntity = ModelEntity(mesh: .generateBox(size: 1),
materials: [cubeMaterial])
let cubeAnchor = AnchorEntity(world: .zero)
cubeAnchor.addChild(cubeEntity)
arView.scene.anchors.append(cubeAnchor)
animate(entity: cubeAnchor,
angle: .pi,
axis: [1, 0, 0],
duration: 4,
loop: true)
cubeEntity.generateCollisionShapes(recursive: false)
arView.installGestures(.all, for: cubeEntity).forEach {
gestureRecognizer in
gestureRecognizer.addTarget(self, action: #selector(handleGesture(_:)))
}
}
func animate(entity: HasTransform,
angle: Float,
axis: SIMD3<Float>,
duration: TimeInterval,
loop: Bool)
{
var transform = entity.transform
transform.rotation *= simd_quatf(angle: angle, axis: axis)
entity.move(to: transform, relativeTo: entity.parent, duration: duration)
guard loop,
animUpdateSubscription == nil
else { return }
animUpdateSubscription = arView.scene.subscribe(to: AnimationEvents.PlaybackCompleted.self,
on: entity,
{ _ in
self.animate(entity: entity,
angle: angle,
axis: axis,
duration: duration,
loop: loop)
})
}
@objc private func handleGesture(_ recognizer: UIGestureRecognizer) {
guard let rotationGesture = recognizer as? EntityRotationGestureRecognizer else { return }
switch rotationGesture.state {
case .began:
var component: ModelComponent = cubeEntity.components[ModelComponent]!.self
component.materials = [SimpleMaterial(color: .orange, isMetallic: true)]
cubeEntity.components.set(component)
case .ended:
var component: ModelComponent = cubeEntity.components[ModelComponent]!.self
component.materials = [SimpleMaterial(color: .white, isMetallic: true)]
cubeEntity.components.set(component)
default:
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment