PysicsBody는 모든 하위 엔티티에도 적용시켜야 작동합니다. 부모엔티티에만 적용하면 작동을 안 해요.
추가: 그냥 generateCollisionShape을 사용하면 콜리전 형태가 convex 쉐잎으로 생성됩니다. 맵처럼 복잡한 형태의 콜리전이 필요하면 generateStaticMesh 쓰시고, 이걸 collisionComponent의 shape으로 설정해주시면 됩니다.
움직이는 객체(캐릭터나 몹)은 그냥 generateCollisionShape 쓰시고
움직임이 없는 객체(맵, 장애물)은 generateStaticMesh 사용하시는 것을 권장드립니다.
이건 convex 콜리전 쉐잎 만들고 physicsBody에 적용하는 코드
var body: some View {
ZStack {
RealityView { content in
guard let game = try? await Entity(
named: "testMapScene", in: testMapBundle
)
else { return }
content.add(game)
if let mapEntity = game.findEntity(named: "testMap") {
mapEntity.generateCollisionShapes(recursive: true)
func applyPhysicsRecursively(to entity: Entity) {
if let collider = entity.components[CollisionComponent.self] {
let body = PhysicsBodyComponent(shapes: collider.shapes, mass: 1.0, mode: .dynamic)
entity.components.set(body)
}
for child in entity.children {
applyPhysicsRecursively(to: child)
}
}
applyPhysicsRecursively(to: mapEntity)
}
}
}
}
이건 concave 콜리전 쉐잎 만들고 physicsBody에 적용하는 코드
if let mapEntity = game.findEntity(named: "testMap") {
Task {
func applyStaticMeshPhysics(to entity: Entity) async {
for child in entity.children {
if let modelComp = child.components[ModelComponent.self] {
let mesh = modelComp.mesh
do {
let shape = try await ShapeResource.generateStaticMesh(from: mesh)
child.components.set(CollisionComponent(shapes: [shape]))
child.components.set(PhysicsBodyComponent(shapes: [shape], mass: 1.0, mode: .static))
} catch { }
}
await applyStaticMeshPhysics(to: child)
}
}
await applyStaticMeshPhysics(to: mapEntity)
}
}