I was making a gesture to let the goose (character) walk, but I had two problems.
1: I added collision and physical body components to the goose and the collided entity, but I found that those physical formations could not completely block the way of the goose. For example, a tree is in front of it. After the goose is blocked, it will cross the tree or run to the top of the tree as long as it is a little faster.
2: Because the knowledge I have accumulated is not very complete, I can control the movement of the goose on the z-axis. I hope that the user's gestures can be realized by dragging back and forth (z-axis), but I can only realize the user's gestures by dragging up and down (y-axis). I hope you can give me some guidance:
GooseOriginalPosition.z + Float(translation.height / 10000)
This is the complete code:
@State var goose: Entity?
@State var isDraggingGoose = false
@State var gooseOriginalPosition = SIMD3<Float>(repeating: 0)
RealityView { content in
if let model = try? await Entity(named: "WorldScene", in: realityKitContentBundle) {
content.add(model)
}
if let gooseEntity = try? await Entity(named: "Goose", in: realityKitContentBundle) {
gooseEntity.scale = SIMD3<Float>(repeating: 0.3)
content.add(gooseEntity)
goose = gooseEntity
}
}
.simultaneousGesture(DragGesture()
.targetedToAnyEntity()
.onChanged { value in
handleDrag(value)
}
.onEnded { _ in
isDraggingGoose = false
gooseTimer?.invalidate()
})
func handleDrag(_ value: EntityTargetValue<DragGesture.Value>) {
guard let goose = goose else { return }
if !isDraggingGoose {
isDraggingGoose = true
gooseOriginalPosition = goose.position(relativeTo: nil)
}
let translation = value.gestureValue.translation
let newPosition = SIMD3<Float>(
gooseOriginalPosition.x + Float(translation.width / 10000),
gooseOriginalPosition.y,
gooseOriginalPosition.z + Float(translation.height / 10000)//I hope the gesture here should be z-axis drag.
)
goose.setPosition(newPosition, relativeTo: nil)
}