How To Remove a SKSpriteNode in didBeginContact - swift

How do I remove a SKSpriteNode in the didBeginContact method?
I have the node as a global variable, (node:SKSpriteNode!), and I change it's position throughout in a couple functions. However, when it is in contact with another object, I want to remove it from the screen. How should I accomplish that?
func didBeginContact(contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch contactMask {
case ColliderType.Star.rawValue | ColliderType.Cup.rawValue:
println("")
default:
return

I don't understand why you are using a global variable when you have multiple balls on screen.
if the categoryBitMask of ball is bitMaskBall, you can remove from parent the node that is in the contact object passed to didBeginContact
func didBeginContact(contact: SKPhysicsContact) {
var ball : SKNode? = nil
// Change it to categoryBitMask of the ball sprite
if contact.bodyA.categoryBitMask == bitMaskBall && contact.bodyB.categoryBitMask == bottomBitMask {
ball = contact.bodyA.node
}
else if contact.bodyB.categoryBitMask == bitMaskBall && contact.bodyA.categoryBitMask == bottomBitMask {
ball = contact.bodyB.node
}
ball?.removeFromParent()
}
The conditions check if any of the bodies involved in the contact is the ball using the categoryBitMask of the ball. Then we extract the node inside the colliding body and finally remove it.

Just remove it from its parent by using removeFromParent() method:
sprite.removeFromParent()

Related

Is there a way to apply sound effects to collisions?

It's my first project with Swift and I'm trying to learn, but I'm stuck and can't find a solution online. Basically, it's a clone of pong, and everything is going good, until now.
My problem it's that I can't understand how to make a sound effect play, once my ball hit the paddles.
Everything else with the collisions is ok, and other sound like the goal one is playing fine. Just can't figure out how i can make a sound play when the two sprites collide.
Here's what I've written:
func didBegin(_ contact: SKPhysicsContact) {
if contact.bodyA.node?.name == "main" && contact.bodyB.node?.name == "ball" || contact.bodyB.node?.name == "main" && contact.bodyA.node?.name == "ball" || contact.bodyA.node?.name == "enemy" && contact.bodyB.node?.name == "ball" || contact.bodyB.node?.name == "enemy" && contact.bodyA.node?.name == "ball" {
ball.run(blipPaddleSound)
}
}
It's all wrong?
I’ve already tried to break the if statement, and already tried with make one of my node run the sound effect (ball.run(‘nameofthesound’). I’ve thought maybe it could be a problem with the file, but other effect don’t play as well in that part of the code. I don’t think there is a problem with the collision, because the ball bounce on the paddle and on the wall without problem
This is the part of the code where I have put all the collision and contact mask:
ball.physicsBody?.contactTestBitMask = 1
ball.physicsBody?.collisionBitMask = 3
ball.physicsBody?.categoryBitMask = 1
main.physicsBody?.contactTestBitMask = 3
main.physicsBody?.collisionBitMask = 1
main.physicsBody?.categoryBitMask = 2
enemy.physicsBody?.contactTestBitMask = 3
enemy.physicsBody?.collisionBitMask = 1
enemy.physicsBody?.categoryBitMask = 2
Most likely you are not setting the SKPhysicsContactDelegate to the Scene
You'll also find that a single collision can fire multiple triggers within the game cycle so you may want to put a variable controlling the sound play so that it doesn't play multiple times per collision
class GameScene: SKScene, SKPhysicsContactDelegate {
private var didCollide = false
func didBegin(_ contact: SKPhysicsContact) {
let object1 = contact.bodyA.node?.name
let object2 = contact.bodyB.node?.name
if object1 == "ball" || object2 == "ball" {
if object1 == "main" || object2 == "main" || object1 == "enemy"|| object2 == "enemy" {
//check if we have just collided within the last 0.3 seconds
if !didCollide {
//set the marker to true so that the sound doesn't repeatedly fire
didCollide = true
//play the sound
ball.run(blipPaddleSound)
//wait 0.3 seconds (give the ball a chance to move away from the object)
self.run(.wait(forDuration: 0.3) {
self.didCollide = false
}
}
}
}
}
}

How do I choose which node I want to contact with, when a collision happens with two nodes at once with SpriteKit?

I have a an iOS app coded in Swift 3 where a ball is shot and bounces off of bricks on the screen. If I have the brick being one PhysicsBody (a rectangle), I can't easily determine which side/corner of the brick is being hit. What I decided to do instead of this, is have each side of the brick be its own separate node. The issue I am having now, is that a ball can't be in contact with two nodes (say the left and bottom) at once. I am decreasing the value of the brick after every contact with the ball, which in turn is decreasing the value by 2 for this one hit. How can I make it so that if a ball hits two nodes, only execute code for one contact?
Sometimes the below code gets executed twice, with the ball contacting with two brickNodes both times.
func didBegin(_ contact: SKPhysicsContact) {
var firstBody:SKPhysicsBody
var secondBody:SKPhysicsBody
let countPoint = true
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if (firstBody.categoryBitMask & ballCategory) != 0 {
if (firstBody.node != nil && secondBody.node != nil){
if (secondBody.categoryBitMask & brickCategory) != 0 {
ballDidHitBrick(ballNode: firstBody.node as! SKShapeNode, brickNode: secondBody.node as! SKShapeNode, decreasePoint: countPoint)
} else if (secondBody.categoryBitMask & roofCategory) != 0 || (secondBody.categoryBitMask & rightWallCategory) != 0 || (secondBody.categoryBitMask & leftWallCategory) != 0 || (secondBody.categoryBitMask & bottomCategory) != 0 {
ballDidHitWall(ballNode: firstBody.node as! SKShapeNode, wallNode: secondBody.node as! SKShapeNode)
} else {
//Nothing as of yet
}
}
}
}
So going along with what Steve has said above, I implemented the code below and I am no longer having dual contacts per update:
if !bricksHit.contains("\(secondBody.node?.name ?? ""), \(firstBody.node?.name ?? "")") {
//If ball hasnt hit the object more than once
bricksHit.append("\(secondBody.node?.name ?? ""), \(firstBody.node?.name ?? "")")
ballDidHitBrick(ballNode: firstBody.node as! SKShapeNode, brickNode: secondBody.node as! SKShapeNode, decreasePoint: countPoint, contact: contact)
}
I also added in the below to my code, which clears the bircksHit after every update:
override func didFinishUpdate() {
bricksHit.removeAll()
}
I would scrap the multiple nodes with multiple bodies, that would yield terrible performance if you have many blocks.
Instead, you should process your work in steps.
During your didBegin phase, you need to keep track of where the contact point is. This can be done with userData
func didBegin(_ contact: SKPhysicsContact) {
var firstBody:SKPhysicsBody
var secondBody:SKPhysicsBody
let countPoint = true
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if (firstBody.categoryBitMask & ballCategory) != 0, (secondBody.categoryBitMask & brickCategory) != 0 {
let userData = firstBody.node!.userData ?? [String,AnyObject]()
let contactPoints = userData["contactPoints"] as? [CGPoint] ?? [CGPoint]()
contactPoints.append(contact.contactPoint) //if need be add other info like the vector or relative to the node
userData["contactPoints"] = contactPoints
}
}
Then in a process later on, like didSimulatePhysics You can evaluate the nodes that were contacted, determine the priority of contact (like the bottom would supersede the sides, or if the velocity x > velocity y, sides, whatever you need to do) and react in this manner.
Note this is only sample code, it will not work verbatim. You will need to structure it into your code to get it to properly work.
Yep - this happens. The consensu of opinion seems to be that if there are multiple simultaneous contact points between 2 physics bodies, SK will call didBegin for every contact point, resulting in multiple calls (in the sam game loop) for the same pair of physics bodies.
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).
Some things you can do include:
If you remove a node that is contacted, check for it being nil before
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 'inactive' property (or similar)
Etc etc.
See this question and answer about SK calling didBegin multiple times for a single contact:
Sprite-Kit registering multiple collisions for single contact
Also SKPhysicsContact contains not only details of the 2 physics bodies that have collided, but also the contact point. From this, and the position properties of the 2 nodes involved, you could indeed calculate which side/corner of the brick is being hit.

Unexpected repeated collisions in SpriteKit

I'm making my first game with Swift and SpriteKit and while I've had collisions working properly for some time now, I recently noticed a huge bug. My collisions can either be the user with and enemy (spaceship against alien) user shooting an enemy (laser against alien). The latter works fine, but recently the collision detection when the ship touches an alien hasn't been working-- normally the alien should be removed from the scene when it touches the so that only a single life (1 of 3 total) is removed. However, the ship looses 3-6 lives upon touch now. Here's the code and where I'd assume the problem is:
This is one of a few contact functions that is then called in the general contact method.
func alien_ship_contact(contact:SKPhysicsContact){
var alien:SKNode? = nil
if contact.bodyA.categoryBitMask == PhysicsCategory.Alien && contact.bodyB.categoryBitMask == PhysicsCategory.Ship{
alien = contact.bodyA.node
}
else if contact.bodyB.categoryBitMask == PhysicsCategory.Alien && contact.bodyA.categoryBitMask == PhysicsCategory.Ship{
alien = contact.bodyB.node
}
else{
return
}
killOffAlien((alien)!)
aliensKilled = aliensKilled + 1
shipLives = shipLives-1
aShip.lives = aShip.lives - 1
print("ship/alien contact")
}
Here is the killOffAlien function:
func killOffAlien(alien:SKNode){
print("Kill off")
//alien.removeFromParent()
func stopMotion(){
alien.physicsBody?.categoryBitMask = 0
alien.physicsBody?.collisionBitMask = 0
alien.physicsBody?.contactTestBitMask = 0
alien.physicsBody?.dynamic = false
alien.physicsBody?.velocity = CGVector(dx:0, dy:0)
alien.removeActionForKey("facialMotion")
}
func removeAlien(){
alien.removeFromParent()
}
let stopMoving = SKAction.runBlock(stopMotion)
let fadeOut = SKAction.fadeOutWithDuration(1)
let removeFromParent = SKAction.runBlock(removeAlien)
let die = SKAction.sequence([stopMoving, fadeOut, removeFromParent])
alien.runAction(die)
}
And here is the general contact method:
func didBeginContact(contact:SKPhysicsContact){
alien_laser_contact(contact)
alien_ship_contact(contact)
....
Any help would be awesome, I would think that upon initial contact the alien has it's bitmask set off from Alien so that in itself would prevent future collisions as every alien should only be able to remove at max one life from the ship.

Swift - Random collisions are not detected

In my game, I use SKSprite. Some collisions are not detected. I did 10 tries, collisions are working well but about 25% of collisions that are supposed to be detected are not detected. I have NO idea why, I tried many things. Collisions are only with nodes of the same category.
I have no idea why randomly some collisions are not made when I can obviously see them, do you have any idea? Thanks for your help.
Here is the code of didBeginContact:
func didBeginContact(contact: SKPhysicsContact) {
var firstBody: SKPhysicsBody = contact.bodyA
var secondBody: SKPhysicsBody = contact.bodyB
if firstBody.categoryBitMask == secondBody.categoryBitMask {
listContacts.append([firstBody.node!,secondBody.node!])
}
}
}
Here is the code of didEndContact:
func didEndContact(contact: SKPhysicsContact) {
var firstBody: SKPhysicsBody = contact.bodyA
var secondBody: SKPhysicsBody = contact.bodyB
if contact.bodyA.categoryBitMask == contact.bodyB.categoryBitMask {
for i in listContacts{
if (i.contains(firstBody.node!) && i.contains(secondBody.node!)){
let findIndex = listContacts.indexOf { $0 == i }
listContacts.removeFirst(findIndex!)
}
}
}
Finally when I declare a new SKSpriteNode I set this:
rectangle.physicsBody = SKPhysicsBody(rectangleOfSize: rectangle.size)
rectangle.physicsBody?.dynamic = true
rectangle.physicsBody?.collisionBitMask = PhysicsCategory.None
usesPreciseCollisionDetection = true doesn't change anything so I don't use usePrecisionCollisionDetection
Every SKSpriteNode has his categoryBitmask and contactTestBitmask equal because only same SKSpriteNodes are supposed to collide.
Also:
physicsWorld.gravity = CGVectorMake(0, 0)
physicsWorld.contactDelegate = self
Finally here is a short video of my game if you want to understand easily what happens (problem of collisions are between rectangles) https://www.youtube.com/watch?v=-pbmKwQiE9U
You seem to be checking if the categoryBitMask of body A equals body B.
if firstBody.categoryBitMask == secondBody.categoryBitMask {
listContacts.append([firstBody.node!,secondBody.node!])
}
}
This will only run an action if a node hits a node with the same categoryBitMask
You should be checking the collisionBitMasks to see if you have a collision, or you can check the name.
For an example using categoryBitMask you can do something like this:
func didBeginContact(contact: SKPhysicsContact) {
var sprite: SKSpriteNode!
if contact.bodyA.categoryBitMask == <your category bitmask> {
sprite = contact.bodyA.node! as! SKSpriteNode
}
else if contact.bodyB.categoryBitMask == <your category bitmask> {
sprite = contact.bodyB.node! as! SKSpriteNode
}
// Do something with sprite....
// You can also create another sprite, and assign it to the other body, and perform functions on it, or both A and B.
// It is good to have different functions you send can send the nodes to once you find out which ones they are.
}
You can do these checks to see which sprites are hitting each other.
I just fixed it! The reason was that in the function "touchesEnded", I had a recursive function that was deleting bad connections in the listContacts!

Stop an action until all gameobjects have stopped colliding with barrier

So far in my code there is a collision detection method that sences when a certain sprite has hit a barrier, and there is also an action sequence I have implemented. In the action sequence I want there to be a wait period where the action stops until a certain amount of sprites have hit the ground (barrier). I've so far got the rotation and cubes falling and the main cube sprite, but the problem I'm trying to solve is getting the cube to stop rotating until all the cubes has hit the barrier. Basically stopping an action until a certain amount of projectile objects has collided with something, then continuing the action. Also the spawning of the cubes is part of the action sequence, so idk what to do without creating clutter in my code.
Please find the below code for reference.
class GameScene:SKScene {
var wait:NSTimeInterval = 0
var blocks = 0
var cube = SKSpriteNode(imageNamed: "cube")
func didBeginContact(contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.categoryBitMask == barrierCategory && secondBody.categoryBitMask == objectCategory {
secondBody.node?.removeFromParent()
counterTest++
print("hello")
}
if (firstBody.categoryBitMask == blockCategory && secondBody.categoryBitMask == barrierCategory) {
blocks++
}
}
override func didMoveToView(view: SKView) {
NSLog("Start") //Using NSLog just to print the current time
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(interval!), target: self, selector: Selector("spawnBlocks"), userInfo: nil, repeats: false)
cube.runAction(recursive())
}
}
func recursive(){
let recursive = SKAction.sequence([
//SHOULD SPAWN ABOUT 10 BLOCKS
SKAction.spawnBlocks,
//WAIT UNTIL THE COLLISION HAS DETECTED 10 BLOCKS HIT THE BARRIER
SKAction.waitForDuration(waitTime),
//CONTINUE THE ROTATION OF THE CUBE SPRITE
SKAction.rotate,
SKAction.runBlock({[unowned self] in NSLog("Block executed"); self.recursive()})
])
runAction(recursive, withKey: "aKey")
}
}
You don't need your action to be recursive. this makes the logic hard to flow and is unnecessary.
If your cube has a continuous and autonomous behaviour, it should manage it itself in a subclass of SKSprite.
I would suggest you create a rotating action and run it "forever" on your cube. Use removeActionWithName when you want it to stop. Add it again when you want the rotation to resume. This will enable you to implement an easy to use "startRotating" / "stopRotating" pair of functions that you can call whenever appropriate.
Same thing with the cube's continuous behaviour, place it in a runBlock action that repeats forever and start/stop other actions when conditions are met.
This will keep all the cube's behaviour within its own class (preferably in a separate file) and avoid you SKView from becoming a big unmanageable blob of code.