I'm writing a 2D game with SpriteKit physics engine in which discs slide on a board (similar to an air hockey game, from a top-down perspective). Most of the physics can be handled with the default properties of SpriteKit but there's one specific case that I think I have to code by myself.
There is a circular hole in the center of the board in which the discs might fall. The hole's size is only slightly larger than the discs' so if the center of a disc passes over the hole slowly enough, the disc should be "attracted" to the center (as it falls off balance into the hole). Also if the whole disc passes over the hole, it should bounce against the border of the hole since it falls entirely. I'm not yet completely sure how to write the physics for that but I think I can come up with something. My question is about where I should write the code for that and what information I can use.
The About SpriteKit page gives the different steps that are performed by SpriteKit on each frame. Using contact collisions with the center of the hole, I can detect when a disc is passing over the hole and so when I need to add forces or correct the movement of the disc. However, I don't know when exactly this contact detection happens in the SpriteKit cycle. It would be nice if it were after the physics simulation and before the rendering of the scene.
Is there a way to write some code to be executed after SpriteKit has computed the new positions of all physics bodies but before it is displayed, while having access to both the new and the old position for each body, similar to oldValue
in a didSet
property observer? If there is no easy way to get the new and old position of a body, I guess I'll have to store the old position myself as a property at each update but I'd rather avoid doing that if possible.
If there is no simple way to "correct" the physics simulation before it is rendered, where should I write the code that simulates the physics of discs interacting with the center hole?
didSimulatePhysics
, which is in your SKScene (just likeupdate
). – GlidermandidBeginContact
takes place afterupdate
but beforedidSimulatePhysics
in a frame cycle. I still don't know if there's a way to write code that would be executed right before or right afterdidSimulatePhysics
that gives access to the old and the new position of the node so that some correction can be done before the change is actually updated on the scene... – Zanapher