Created
November 28, 2024 14:49
-
-
Save Matt54/4ff9f012cb240aba1bc07ea81e413a43 to your computer and use it in GitHub Desktop.
RealityView with a grid of animating cloned turkey model entities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import RealityKit | |
struct TurkeyClonesAnimationView: View { | |
let scale: Float = 0.02 | |
let horizontalCount: Int = 4 | |
let horizontalSpacing: Float = 0.0375 | |
let verticalCount: Int = 2 | |
let verticalSpacing: Float = 0.05 | |
var body: some View { | |
RealityView { content in | |
let modelEntity = try! await loadModelEntity() | |
for yIndex in 0...verticalCount { | |
for xIndex in 0...horizontalCount { | |
let clone = modelEntity.clone(recursive: false) | |
clone.transform.translation.x -= (horizontalSpacing*Float(horizontalCount)*0.5 - horizontalSpacing * Float(xIndex)) | |
clone.transform.translation.y -= (verticalSpacing*Float(verticalCount)*0.5 - verticalSpacing * Float(yIndex)) | |
content.add(clone) | |
for animation in clone.availableAnimations { | |
clone.playAnimation(animation.repeat(duration: .infinity), | |
transitionDuration: 0, | |
startsPaused: false) | |
} | |
} | |
} | |
} | |
} | |
func loadModelEntity(url: URL = URL(string: "https://matt54.github.io/Resources/Animation_Walking.usdz")!) async throws -> ModelEntity { | |
let (downloadedURL, _) = try await URLSession.shared.download(from: url) | |
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! | |
let destinationURL = documentsDirectory.appendingPathComponent("downloadedModel.usdz") | |
if FileManager.default.fileExists(atPath: destinationURL.path) { | |
try FileManager.default.removeItem(at: destinationURL) | |
} | |
try FileManager.default.moveItem(at: downloadedURL, to: destinationURL) | |
let entity = try await ModelEntity.init(contentsOf: destinationURL) | |
try FileManager.default.removeItem(at: destinationURL) | |
entity.scale *= 0.02 | |
entity.transform.translation.y -= 0.1 | |
return entity | |
} | |
} | |
#Preview { | |
TurkeyClonesAnimationView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment