Hello
//modelEntityClone.generateCollisionShapes(recursive: true)
modelEntityClone.physicsBody = PhysicsBodyComponent(massProperties: .default, material: .default, mode: .dynamic)
as above, I have modelEntity placed on arscene,
and moving modelentity is very well !
but as soon as adding generateCollisionShape ,
modelentity is not moving anymore,
how can I use both moving entity and generate collision ?
Post
Replies
Boosts
Views
Activity
Hello
I made a code that
there is Entity loaded on ar, and I placed cube to position which is SIMD3
what I want is that moving entity loaded on ar to move to the location where cube is located.
how I did is
self.modelentity2!.move(to: Transform(scale: simd_make_float3(1, 1, 1),
rotation: (anchorEntity.transform.rotation),
translation: newTranslation),
relativeTo: nil,
duration: 2,
timingFunction: .linear)
self.modelentity2 is entity that I loaded
and anchorEntity is that I place when user tap
modelentity2 is moving very well to anchorEntity
but the problem is that modelentity2 should face toward anchorEntity but it looks rotating randomly or not rotating at all.
how can I move entity face to anchorEntity ?
I placed 3d object to ARViewController
after 3 seconds of placing object, then I want to rotate object by 90degree
arView.scene.addAnchor(anchorEntity)
DispatchQueue.main.asyncAfter(deadline: .now() + 3){
print("after 3 sec ! ")
let radians = 90.0 * Float.pi / 180.0
anchorEntity.orientation = simd_quatf(angle: radians, axis: SIMD3(x: 0, y: 1, z: 0))
}
it works very well but the problem is that I want to smooth rotation , as you can see short video, it suddenly rotate which seem weird.
how can I do this ?
https://youtu.be/Ixk2elm-bfU
I want to move toy_drummer entity with rotating toward other model entity.
as you can see video, firstly, it move very well to left one
then, I touch downward box entity but it move weird.
video is
youtu.be/3rb9W334Uwg
modelentity2 is the entity that I want to move
modelentityleft & modelentityright are the entity that modelentity2 should go to , so I can call objective entity
*code
when I touch left box entity to move,
if(entity?.parent?.name=="left"){
self.parent.value4="leftarea"
if(oktoadd){
self.counting = self.counting + 1
if(counting==1){
var position = firstResult.position
let currentMatrix = self.modelentityleft!.transform.matrix
let rotation = simd_float4x4(SCNMatrix4MakeRotation( -90.0 * .pi/180, 0,1,0))
let transform = simd_mul(currentMatrix, rotation)
self.modelentity2!.move(to: transform,
relativeTo: self.me,
duration: 1,
timingFunction: .linear)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.1) {
counting=0
}
}
}
}
when click downward box entity,
if(ent
ity?.parent?.name=="down"){
self.parent.value4="downarea"
if(oktoadd){
self.counting = self.counting + 1
if(counting==1){
self.parent.value4="animating"
var position = firstResult.position
let currentMatrix = self.modelentitydown!.transform.matrix
let rotation = simd_float4x4(SCNMatrix4MakeRotation( 90.0 * .pi/180, 0,1,0))
let transform = simd_mul(currentMatrix, rotation)
print("added moving ...")
self.modelentity2!.move(to: transform,
relativeTo: self.me,
duration: 1,
timingFunction: .linear)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.1) {
counting=0
}
}
}
}
in my code, I firstly change rotation toward objective entity then move
is there any way that I can do it more simply? (also wonder I hardcoded radian by 90 or -90 , any way to fix it by getting objective entity's position? )
I tap screen and get result hit point.
from that point, I want to measure distance to a 3d object placed on ar view.
code is
*for placing 3dobject
let anchorEntity = AnchorEntity(anchor: anchor)
anchorEntity.addChild(modelEntityClone)
arView.scene.addAnchor(anchorEntity)
*for point to measure distance to 3dobject
guard let rayResult = self.view!.ray(through: normalizedIndexPoint)else {return}
let results = self.view!.scene.raycast(origin: rayResult.origin, direction: rayResult.direction)
if let firstResult = results.first {
var position = firstResult.position
var distanceing = distance(firstResult.position, self.me!.position)
}
I pointed very close to 3d object but it's a bit far saying 30 cm... or so,
I found out that once I close to world origin, than it become almost 0...
how can I measure from 3d object not from world origin?
Hello !
The only way that I can use multiple animation is to have multiple USDZ with single animation
according to WWDC example
https://developer.apple.com/videos/play/wwdc2021/10074/
todo so, I should have file with single animation
but many sources like Sketchfab.. etc
it has single GLTF , USDZ file with multiple animations,
I have blender but it's too difficult to export each animation to each modeling file.
can anyone let me know how to split file by animation?
https://developer.apple.com/videos/play/wwdc2021/10074/
with example that apple provide, there's dive app.
in app sampel code, there's animation sequence which is done by octopus entity.
I think this is the only way that I can do multiple animation with swift / USDZ form.
the problem is that I can't reproduce animation sequence,
so, I tweaked a little bit of sample code.
firstly,
when scene is up,
on UnderwaterView.swift,
load models function,
uncomment if state so that setupOctopus is triggered.
so, when ar app is on, octopus is appear on scene.
I changed a little bit of hidingLocation so that after 3seconds of appear octopus, it move with animation.
but the problem is octopus is moving but it shows no animation... what may be the problem?
struct OctopusSystem: RealityKit.System {
init(scene: RealityKit.Scene) {}
func update(context: SceneUpdateContext) {
let scene = context.scene
for octopus in scene.performQuery(OctopusComponent.query) {
print("oc 1111")
guard octopus.isEnabled else { continue }
print("oc 2222")
guard var component = octopus.components[OctopusComponent.self] as? OctopusComponent else { continue }
// guard component.settings?.octopus.fearsCamera ?? false else { return }
print("oc 3333\(component.state)")
switch component.state {
case .hiding:
print("oc 44444")
guard let camera = scene.performQuery(CameraComponent.query).first(where: { _ in true }) else { continue }
print("oc 555")
let fearDistance: Float = 1.0
let distanceToCamera = octopus.distance(from: camera)
print("oc 5555")
guard distanceToCamera < fearDistance else { continue }
print("oc 6666")
var hidingLocation = octopus
hidingLocation.transform.translation.x=hidingLocation.transform.translation.x-0.01
print("oc 7777")
// let distance = octopus.distance(from: hidingLocation)
// guard distance > fearDistance else { continue }
// print("oc 88")
var duration = 30.5
print("oc du...")
// Animations
DispatchQueue.main.asyncAfter(deadline: .now() + 3){
do {
let fixedTime
= component.animations.crawl2Swim.definition.duration
+ component.animations.swim2crawl.definition.duration
duration = max(fixedTime, duration)
let swimDuration = duration - fixedTime
let swimCycleDuration = component.animations.swim.definition.duration
let swimCycles = Int(swimDuration / swimCycleDuration)
duration = fixedTime + Double(swimCycles) * swimCycleDuration
if let animation = try? AnimationResource.sequence(with: [
component.animations.crawl2Swim,
component.animations.swim.repeat(count: swimCycles),
component.animations.swim2crawl
]) {
print("oc playanimation")
octopus.playAnimation(animation)
}
}
octopus.move(to: hidingLocation.transform, relativeTo: nil, duration: duration)
}
// component.state = .swimming(duration)
case .swimming(var time):
time -= context.deltaTime
component.state = time < 0 ? .hiding : .swimming(time)
}
octopus.components.set(component)
}
}
}
there's position which is simd3
and there 's anchorEntity.
I want to get distance between two.
how I did is
var distance = distance(position, ( self.modelentity.position(relativeTo:nil) )
var distance = distance(position, ( self.modelentity.position )
but both failed because it seems calculating distance between world origin anchor
not distance between position to self.modelentity.
how can I calculate distance ?
Hello...
I really literally can't find any article addressing animation In USDZ format more detail...like transitioning multiple animation...blending each animation...
even there's api for blend and transition.
how can I find any source for detailing animation ?
maybe it's better to use unity...
I made most of app but can't find a way to animate multiple animation.
Hello :)
I'm trying to make Apple Watch app that can detect hand wash is finished.
I followed workout app that apple provided,
and succeed in getting hand wash count information .
but how can I detect hand wash event when app is not foreground or executed.
my full code is as below
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
The start view.
*/
import SwiftUI
import HealthKit
var healthStore: HKHealthStore!
struct StartView: View {
@State var count: Int = 0
//
// ContentView.swift
// handwash
//
// Created by pedro jung on 2022/06/09.
//
var body: some View {
Button(action: {
checkHealthKit()
}, label: {
Text("Button\(self.count)")
})
}
func checkHealthKit() {
print(count)
healthStore = HKHealthStore()
let healthTypes = Set([
HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!
])
healthStore.requestAuthorization(toShare: nil, read: healthTypes)
{ (success, error) in
fetchHandWashing()
}
}
func fetchHandWashing() {
let now = Date()
let calendar = Calendar.current
let yesterday = calendar.date(byAdding: .day, value: -1, to: calendar.startOfDay(for: now))
let predicate = HKQuery.predicateForSamples(withStart: yesterday, end: now, options: [])
let sortDescriptor = [NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true)]
let washingEvent = HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!
let query = HKSampleQuery(sampleType: washingEvent,
predicate: predicate,
limit: HKObjectQueryNoLimit,
sortDescriptors: sortDescriptor) {
(query, results, error) in
guard error == nil else { print("error"); return }
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
format.timeZone = TimeZone(identifier: "Asia/Tokyo")
print("\(format.string(from: yesterday!)) - \(format.string(from: now)) r \(results)esult 🥳:")
if let tmpResults = results as? [HKCategorySample] {
print(tmpResults.count)
self.count=tmpResults.count
tmpResults.forEach { (sample) in
print(sample)
}
}
}
healthStore.execute(query)
healthStore.enableBackgroundDelivery(
for: washingEvent,
frequency: .immediate,
withCompletion: { succeeded, error in
guard error != nil && succeeded else {
self.count = self.count+1
//send information!
return
}
// Background delivery is enabled
}
)
let query2 = HKObserverQuery(
sampleType: washingEvent,
predicate: nil,
updateHandler: { query, completionHandler, error in
defer {
completionHandler()
}
guard error != nil else {
return
}
// TODO
})
healthStore.execute(query2)
}
}
https://developer.apple.com/documentation/clockkit/creating_and_updating_a_complication_s_timeline
I just run sample app to check background delivery on health kit.
I added caffein on my health app on phone.
but it dosen't triggered on obeserver processUpdate function.
func processUpdate(query: HKObserverQuery,
completionHandler: @escaping () -> Void,
error: Error?) {
print("processUpdate come!!!!")
logger.debug("Received an update from the background observer query.")
// Check for any errors that occur while setting up the observer query.
guard error == nil else {
logger.error("Unable to set up a background observer query: \(error!.localizedDescription)")
fatalError()
}
logger.debug("Responding to a background query.")
Task {
// Load the updated data from the HealthKit Store.
let success = await loadNewDataFromHealthKit()
// Check for any errors.
guard success == true else {
logger.error("Unable to query for new or deleted caffeine samples.")
fatalError()
}
// Call the completion handler when done.
completionHandler()
}
}
I want to query to washing event.
but washing hand is HKCategoryType so I can't use HKStatiticsCollectionQueryDescriptor because it only accept HKQuantitySample.
is there a way that I can use it ?
let stepType = HKQuantityType(.stepCount)
let stepsThisWeek = HKSamplePredicate.quantitySample(type: stepType, predicate: thisWeek)
let yesterday = calendar.date(byAdding: .day, value: -1, to: calendar.startOfDay(for: now))
let every5 = DateComponents(minute:5)
let healthTypes = Set([
HKCategoryType.categoryType(forIdentifier: .handwashingEvent)!
])
let sumOfStepsQuery = HKStatisticsCollectionQueryDescriptor(
predicate: stepsThisWeek,
options: .cumulativeSum,
anchorDate: endDate,
intervalComponents: every5)
do {
let updateQueue = sumOfStepsQuery.results(for: store)
// Wait for the initial results and updates.
updateQueue = Task {
for try await results in updateQueue {
// Use the statistics collection here.
}
}
} catch {
//handle error
print(error)
}
reference : https://wjwickham.com/posts/refreshing-data-in-the-background-on-watchOS/
on init function ,
which mean, for every 5 min it should come to
handle function in Extension Delegate.swift
but it won't come to handle any
anything else that I should do ?
let preferredDate = Date().addingTimeInterval(60 * 5)// 5min later
preferredDate, userInfo: nil) { (error) in
WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: preferredDate, userInfo: nil) { (error: Error?) in
guard error == nil else {
print("Couldn't schedule background refresh.")
return
}
print("Scheduled next background update task for: \(preferredDate)")
}
ExtensionDelegate.swift
//
// ExtensionDelegate.swift
// Coffee Tracker WatchKit Extension
//
// Created by pedro jung on 2022/06/15.
// Copyright © 2022 Apple. All rights reserved.
//
import Foundation
import WatchKit
class ExtensionDelegate: NSObject,ObservableObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
print("applicationDidFinishLaunching")
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
print("applicationDidBecomeActive")
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillResignActive() {
print("applicationWillResignActive")
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
for task in backgroundTasks {
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
BackgroundService.shared.updateContent()
backgroundTask.setTaskCompletedWithSnapshot(false)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
BackgroundService.shared.handleDownload(urlSessionTask)
default:
task.setTaskCompletedWithSnapshot(false)
}
}
}
}
I also check other way
after checking reply of below link
https://developer.apple.com/forums/thread/661892
but with no luck ...
import SwiftUI
import WatchKit
@main
struct CoffeeTrackerApp: App {
@Environment(\.scenePhase) var scenePhase
@WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate
@SceneBuilder var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
}
.onChange(of: scenePhase) { phase in
switch phase {
case .active:
print("\(#function) REPORTS - App change of scenePhase to ACTIVE")
case .inactive:
print("\(#function) REPORTS - App change of scenePhase Inactive")
case .background:
let preferredDate = Date().addingTimeInterval(60 * 1)// One hour later
// delegate.shared().scheduleBackgroundRefresh(withPreferredDate: preferredDate, userInfo: nil) { (error) in
WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: preferredDate, userInfo: nil) { (error: Error?) in
guard error == nil else {
print("Couldn't schedule background refresh.")
return
}
print("Scheduled next background update task for: \(preferredDate)")
}
delegate.test()
default:
print("\(#function) REPORTS - App change of scenePhase Default")
}
}
}
}
}
let stagePredicate = HKCategoryValueSleepAnalysis.predicateForSamples(.equalTo,value: .asleepREM)
let queryPredicate = HKSamplePredicate.sample(type: HKCategoryType(.sleepAnalysis), predicate: stagePredicate)
let sleepQuery = HKSampleQueryDescriptor(predicates: [queryPredicate], sortDescriptors: [])
do{
let sleepSample = try await sleepQuery.result(for: store)
print("sleep sample ")
print(sleepSample)
with health app on iOS ,
it says I did rem sleep for 59 minutes.
but all sum of sleep sample time is not 59 but 3.7hours.
time is also not accurate.
sleepSample log is as below
what may be the problem?