I am fairly new to Swift and just started playing with RealityKit and ARKit. I am working on a personal project where I would like to have a 3D object stick to the camera in first person. Similar to the AR Angry birds or any FPS game. I have seen a few examples in SceneKit or SpriteKit, I am sure it is just a misunderstanding of how anchoring entities works.
My main question is:
- How would I go about sticking a reality object I created in Reality Composer to the camera in first person? I want to create a Reality Scene, in this case an arm cannon and upon tapping it shots.
Below is the code for my ViewController
extension ViewController: ARSessionDelegate
{
func session(_ session: ARSession, didUpdate frame: ARFrame)
{
guard let arCamera = session.currentFrame?.camera else { return }
// Probably where I update the location of my reality experience
}
}
class ViewController: UIViewController
{
@IBOutlet var arView: ARView!
override func viewDidLoad()
{
super.viewDidLoad()
arView.session.delegate = self
// Load the "ArmCannon" scene from the "Experience" Reality File
let armCannonAnim = try! Experience.loadArmcannon()
// Create Anchor to anchor arm cannon to
let anchor = AnchorEntity(.camera)
anchor.transform = arView.cameraTransform
// Add the anchor to the scene
arView.scene.addAnchor(anchor)
// Setup tap gesture on arm cannon
let tapGesture = UITapGestureRecognizer(target: self, action:#selector(onTap))
arView.addGestureRecognizer(tapGesture)
// Add the the cannon animation to arView
arView.scene.anchors.append(armCannonAnim)
}
@IBAction func onTap(_ sender: UITapGestureRecognizer)
{
let tapLocation = sender.location(in: arView)
// Get the entity at the location we've tapped, if one exists
if let cannonFiring = arView.entity(at: tapLocation)
{
print(cannonFiring.name)
print("firing Cannon")
}
}
}
I have looked at and read Track camera position with RealityKit and Where is the .camera AnchorEntity located?