I am having some issues with collisions in spritekit and the way that the code is firing. I am using physics contact delegate and standard bit masks. The collisions only occur between two objects at a time. I want the collision to be detected and then execute the following code once. Unfortunately, there is contact between the objects at multiple points which results in the code firing more than once. My code is set up to remove the node before the code is run but I am still suffering this issue. How can I ensure that a collision will be detected at a single point or that the code will only be run once, thanks in advance.
-
6What collisions? What framework are you referring to? Please [edit] your question to make it clear (do not reply with a comment). – rmaddy Jan 14 '19 at 15:34
-
You forgot to post your code. – takendarkk Jan 14 '19 at 17:34
-
1Your edit doesn't clarify anything. Is this SpriteKit? SceneKit? ARKit? Something else? Where's your relevant code? – rmaddy Jan 14 '19 at 17:40
-
Yes this is sprite kit. The code needs something added to it to allow for a collision to only call a function once. When contact is made on a single point this is how it functions, yet, when the broad side of two of the objects collide there are several points of contact and thus multiple firings. – Keegan Tountas Jan 15 '19 at 00:05
2 Answers
Your question is a bit unclear, but i think i might have had a similar issue in the past.
Have you tried to set the SKPhysicsBody (of the node you want to remove after the collision) to nil? If thats the first thing you do after a collision it won't register any other collisions and only execute any code you have setup that one time.
- 83
- 8
-
That won’t work - SK has already detected multiple collisions and queued them for processing by didBegin. Removing a physicsBody now won’t prevent these collision that have already happened but will cause an error in subsequent calls to didBegin, as the Pb won’t be there. – Steve Ives Apr 06 '19 at 09:23
Yep - this happens. The way to handle it (you can't get sprite-kit to NOT call didBegin multiple times in some circumstances) is to make sure that your contact code accommodates this and that handling the contract multiple times does not cause a problem (such as adding to the score multiple times, removing multiple lives, trying to access a node or physicsBody that has been removed etc).
There is a discussion here: Sprite-Kit registering multiple collisions for single contact
Some things you can do include:
- If you remove a node that is contacted, check for it being
nilbefore you remove it (for the duplicate contacts) - Add the node to a set and then remove all the nodes in the set in
didFinishUpdate - Add an 'inactive' flag' to the node's
userData - Make the node a subclass of SKSpriteNode and add an
inactiveproperty - Etc etc.
- 7,894
- 3
- 24
- 55