6

How can I get the current velocity of a SCNPhyisicsBody?

The velocity property does always return (0.0, 0.0, 0.0), and the physicsBody of the prensetationNode of my SCNNode is also nil.

Max
  • 2,699
  • 2
  • 27
  • 50

2 Answers2

7

You can get the "current" velocity with

physicsBody.velocity

But this is valid only within the "game loop" callbacks (updateAtTime, didApplyAnimations, didSimulatePhysics, will/didRenderScene).

Toyos
  • 4,024
  • 15
  • 16
  • 3
    How did you become aware of this? Can't see this blatantly mentioned in the docs. – Confused Jul 07 '15 at 17:50
  • Does this mean you can only set `velocity` within game loop callbacks as well? Setting velocity so far doesn't seem to work, but will try the game loop callbacks. @Confused – Crashalot Jan 28 '17 at 09:11
  • 1
    I will have to build a project and check. Haven't tinkered with SceneKit physics for a long while. @Crashalot – Confused Jan 28 '17 at 09:39
  • 2
    @Confused ... just tried it, and setting the velocity property directly seems to have no effect (even within game loop functions). – Crashalot Jan 28 '17 at 09:47
  • 1
    @Confused were you able to set the velocity property directly to move SCNNodes? thanks for your help! – Crashalot Jan 28 '17 at 23:35
  • The answer is wrong. .velocity works **at any time**. it "reports" the velocity as last calculated in the game loop. As with @Crashalot I am finding it hard to set the velocity. – Fattie Dec 20 '22 at 13:15
1

...in your view controller, you have to use SCNSceneRendererDelegate protocol like

class GameViewController: UIViewController,SCNSceneRendererDelegate{...

and in the viewDidLoad method set the SCNView delegate to scnView.delegate=self

Then you can implement for example

func renderer(renderer: SCNSceneRenderer, didRenderScene scene: SCNScene, atTime time: NSTimeInterval) {

    let scnView = self.view as! SCNView
    let scene = scnView.scene
    let compass = scene?.rootNode.childNodeWithName("ObjectName", recursively: true)

    print((compass?.physicsBody?.angularVelocity)!)
}

this works in my case. hope it helps a bit!

nik
  • 181
  • 1
  • 6