Search code examples
swiftswiftuiscenekit

Best way to move a physicsBody of type .dynamic in SceneKit (SwiftUI)


What is the best approach to move a player object in SceneKit?

Setup:

Currently I have a flat ground with a player object on it. Both objects have a SCNPhysicsBody. The ground is of type .static and the player is of type .dynamic.

Goal:

I want the player to move randomly on the ground.

Tried:

  • SCNAction: Does not seem to work together with the SCNPhysicsBody.
  • SCNTransaction: Does not seem to animate at all - Ends up at the final position instantly
  • .applyForce: Works so far, but seems to me a bit complex and clumsy in terms of execution and duration

Is there another way to move a game character? What is the best practice?


Solution

  • A .dynamic physics body is NOT intended to be moved by something else than the SceneKit Physics Engine itself. This means, things like gravity, force-fields or collisions with other ojects or the floor will move and control the body. If you try to influence such a body, this will mess up very likely.

    There are a few things like clearAllForces or a resetTransform command on the physics body, which allows you to do kind of influence stuff in combination with Actions or Transitions, but this is a very high cost to overall performance and has to be done on each frame to work properly. It's not recommended for continous gameplay situations.

    Try to make your player using a .kinematic physics body instead. Apple released some years ago the so called FOX demo app which you can find here. Try to grab the gameplay control. It's a very good approch to imitate a real .dynamic physics body. Good luck.