So I'm developing a game using SpriteKit. And to make the game more interesting I decided to use UIDynamicAnimator to add some physics to the UIKit elements within my game. Everything works great except there is one major problem. The moment I alloc/init a UIDynamicAnimator like so:
animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
The physics bodies in my game get completely offset. Even if I don't specify a reference view the physics still get offset.
What's strange is that i'm creating the UIDynamicAnimator in a completely separate ViewController so it's not like it's sharing the same reference view or something like that.
Update: Even the act of simply creating a UIDynamicItemBehavior like so:
UIDynamicBehavior* a = [[UIDynamicBehavior alloc] init];
messes up my scene's physics.
I'm assuming this is an internal bug with the physics engine that SpriteKit and UIDynamics share.
Anyone have any suggestions?
Ok I found a pretty hacky solution. All you need to do is use the UIDynamics framework in some way before presenting your SKScene. For example, simply running this one line of code before presenting your scene will remove the weird physics bug caused by simultaneously using SpriteKit and UIDynamics at the same time:
I'm assuming internally this prepares the physics engine in such a way that sprite kit physics will behave normally. Unfortunately I do not trust this solution because it might not work one day and my entire game would suffer because of it.
So as an alternative to the UIDynamics framework I've decided to just use UIView Animation to replicate some of the interesting physics effects that I got with the UIDynamics Framework.
EDIT FOR IOS 8 According to doctordoder, this bug still exists in iOS 8, and this workaround still works.
Note that in iOS 9: the @Epic Byte's solution still do the half workaround.
It starts the physics engine earlier (before we
initialize
SpriteKit
game etc.) but unfortunately it mixes it up.And
allocation
andinit
theUIDynamicAnimator
during theSpriteKit
game will cause thephysicsWorld
and it's properties likegravity
act differently.Also it seems like the
physicsWorld
is removed for a short time (switching engines?) duringUIDynamicAnimator
initialization.Conclusion:
Alloc and init
UIDynamicAnimator
asap and handle your physics world differently e.g. call[UIDynamicAnimator new];
in delegate'sdidFinishLaunchingWithOptions
or