ios - SpriteKit detecting multiple collision instead of once ( Swift 3) -
there 3 skspritenode in skscene class. 1 of them player , other ones gold , unvisible finish object such when player touch it, game finished. problem when player collide gold, gold budget should increase 50 gold. however, xcode detect multiple collision , gold budget increasing multiple times. 50-60 collision detected instead of 1 collision. researched how solve problem. found should use bool, tried set bool didn't solve problem. there can me how detect 1 collision? here gamescene class codes :
import spritekit import gameplaykit class level3: skscene, skphysicscontactdelegate { let playerfilename = "player" let starfilename = "50gold" let goalfilename = "goal" let playercategory : uint32 = 0x1 << 1 let goalcategory : uint32 = 0x1 << 2 let starcategory : uint32 = 0x1 << 3 override func didmove(to view: skview) { super.didmove(to: view) physicsworld.contactdelegate = self let goal = childnode(withname: goalfilename) as! skspritenode let player = childnode(withname: playerfilename) as! skspritenode let star = childnode(withname: starfilename) as! skspritenode player.physicsbody!.categorybitmask = playercategory goal.physicsbody!.categorybitmask = goalcategory star.physicsbody?.collisionbitmask = 1 player.physicsbody?.collisionbitmask = 1 goal.physicsbody?.collisionbitmask = 1 goal.physicsbody?.isdynamic = true goal.physicsbody!.contacttestbitmask = playercategory player.physicsbody?.isdynamic = true star.physicsbody?.isdynamic = true player.physicsbody?.contacttestbitmask = starcategory star.physicsbody?.categorybitmask = starcategory func didbegin(_ contact: skphysicscontact) { // 1 var firstbody: skphysicsbody var secondbody: skphysicsbody // 2 if contact.bodya.categorybitmask < contact.bodyb.categorybitmask { firstbody = contact.bodya secondbody = contact.bodyb } else { firstbody = contact.bodyb secondbody = contact.bodya } if firstbody.categorybitmask == playercategory && secondbody.categorybitmask == goalcategory { contact.bodyb.node?.removefromparent() } if firstbody.categorybitmask == playercategory && secondbody.categorybitmask == starcategory { playsceneviewcontroller.instance.gold += 50 print(playsceneviewcontroller.instance.gold) contact.bodyb.node?.removefromparent() } } } }
yep - happens. way handle (you can't sprite-kit not call didbegin multiple times in circumstances) make sure contact code accommodates , handling contract multiple times not cause problem (such adding score multiple times, removing multiple lives, trying access node or physicsbody has been removed etc).
for more detail , possible solutions, see answer : https://stackoverflow.com/a/44384390/1430420
Comments
Post a Comment