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 ?
Selecting any option will automatically load the page
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 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)
}
}
}
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)
}
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?
Topic:
App & System Services
SubTopic:
Core OS
Tags:
watchOS
Health and Fitness
HealthKit
wwdc2022-10133
it really weird. I can't add device because it is grayed out and can't add more uuid.
I checked Continue button but it says as first pic, I can add more 45 iPhone but + button is still grayed out
it is way above of control panel....
the code I show usdz modeling is as below
`RealityView{
content in
let entity = try! await Entity(named: "idle")
entity.setScale([0.15,0.15,0.15], relativeTo: entity)
// Enable interactions on the entity.
entity.components.set(InputTargetComponent())
entity.components.set(CollisionComponent(shapes: [.generateBox(size: [2,2,2])] ) )
content.add(entity )
}`
wow, this drive me crazy.
I have plenty of storage left after reboot after remove xcode and re install dont solve this problem.
funny thing is that editing as is code is okay. but just add new line cause infinite loading