Checking current spritenode - swift

Have that situation: I have bouncing red ball and several randomly generated platforms.
In case of contact with bottom of the platform ball should pass platform through. In other case, it will be top of platform and ball should bounce. I changing .collisionBitMask and .contactTestBitMask params for player to pass through platform or bounce on it. But my code working only for the last one platform, you can see on screenshot. For other platforms not working - ball pass it through from the top side too. I have array of that platforms and don't know how to check current platform.
Here is part of my code:
var platforms = [SKSpriteNode]()
....
extension GameScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
let floor = BitMaskCategory.floor
let player = BitMaskCategory.player
let platformCategory = BitMaskCategory.platform
let bodyA = contact.bodyA.categoryBitMask
let bodyB = contact.bodyB.categoryBitMask
if bodyA == player && bodyB == platformCategory || bodyA == platformCategory && bodyB == player {
for platform in platforms {
if self.player.position.y > platform.position.y {
self.player.physicsBody?.collisionBitMask = floor | platformCategory
self.player.physicsBody?.contactTestBitMask = floor | platformCategory
} else if self.player.position.y < platform.position.y {
self.player.physicsBody?.collisionBitMask = floor
self.player.physicsBody?.contactTestBitMask = floor
}
}
}
}
func didEnd(_ contact: SKPhysicsContact) {
let player = BitMaskCategory.player
let bar = BitMaskCategory.platform
let floor = BitMaskCategory.floor
let bodyA = contact.bodyA.categoryBitMask
let bodyB = contact.bodyB.categoryBitMask
if bodyA == bar && bodyB == player || bodyA == player && bodyB == bar {
for platform in platforms {
if self.player.position.y > platform.position.y {
self.player.physicsBody?.collisionBitMask = floor
self.player.physicsBody?.contactTestBitMask = floor
}
}
}
}
}
So, I don't know how to check current platform. If I placing 3 constant platforms by hand all is working fine :D
Please help, don't know how to realize this task.

I have this approach for solutions (Red platforms)
You can get code example here: https://github.com/Maetschl/SpriteKitExamples/tree/master/PlatformTest
This use object velocity for getting the direction and add collision mask
override func update(_ currentTime: TimeInterval) {
player.physicsBody?.collisionBitMask = 0b0000 // Reset the mask
// For UP only Platform
if (player.physicsBody?.velocity.dy)! < CGFloat(0.0) {
player.physicsBody?.collisionBitMask |= 0b0001 // The pipe | operator adds the mask by binary operations
}
// For Down only platforms
if (player.physicsBody?.velocity.dy)! > CGFloat(0.0) {
player.physicsBody?.collisionBitMask |= 0b0010 // The pipe | operator adds the mask by binary operations
}
}

Related

Emitter not adding where players position is

I am trying to get a player to collide with a SKNode. Doing so, I want a particle to display an exposition where the SKNode just was(player) and display the effect. When I tried to create this, the emitter is not displaying where the player is. How can I fix this?
func didBegin(_ contact: SKPhysicsContact) {
let bodyA = contact.bodyA
let bodyB = contact.bodyB
if bodyA.categoryBitMask == 1 && bodyB.categoryBitMask == 2 || bodyB.categoryBitMask == 1 && bodyA.categoryBitMask == 2 {
let player = SKNode(fileNamed: "player")
let explostion = SKEmitterNode(fileNamed: "explosion.sks")
let addExplosion = SKAction.run {
player?.addChild(explostion!)
}
let seq = SKAction.sequence([addExplosion])
self.addChild(explostion!)
self.run(seq)
}
}
Probably one of physics body belongs to player's node? So you just can access it from body. For example let's player's body - is bodyA:
if bodyA.categoryBitMask == 1 && bodyB.categoryBitMask == 2 || bodyB.categoryBitMask == 1 && bodyA.categoryBitMask == 2 {
let player = bodyA.node
let explostion = SKEmitterNode(fileNamed: "explosion.sks")
player.addChild(explostion!)
}
}

Node on top of another Node, both with Physics Bodies, Only want to detect most top physics body - SpriteKit / Swift

Creating a game in Swift and SprieKit.
I have 2 nodes, a BridgeNode and WaterNode. One on top of the other.
Both have physics bodies to detect when the player is either on the bridge on in the water. Both nodes are added independently as child nodes of the Scene.
When the player node jumps onto the Bridge, DidBegin detects contact with
both the Water and Bridge nodes. I only want it to detect the Bridge node as the player is safely on the Bridge OR if the player is in the water.
func didBegin(_ contact: SKPhysicsContact) {
// Did Begin Contact - Contact Testing and actions
let player1 = (contact.bodyA.categoryBitMask == player1Mask) ? contact.bodyA : contact.bodyB
let other = (player1 == contact.bodyA) ? contact.bodyB : contact.bodyA
if other.categoryBitMask == bridgeMask {
print("BRIDGE CONTACT")
}
else if other.categoryBitMask == waterMask {
// Contacted Water
print("WATER CONTACT")
}
}
The console is printing both print statements always in a random order.
Hope someone can help me to just detect one or the other.
You mentioned that it is a top-down game, so when you have the bridge on top of the water the player will obviously contact both at the same time, there is no "blocking" of the physicsBody underneath the bridge. You need to do something like this in your SKPhysicsContactDelegate:
var playerIsOnBridge = false
func didBegin(_ contact: SKPhysicsContact) {
let player1 = (contact.bodyA.categoryBitMask == player1Mask) ? contact.bodyA : contact.bodyB
let other = (player1 == contact.bodyA) ? contact.bodyB : contact.bodyA
if other.categoryBitMask == bridgeMask || playerIsOnBridge {
playerIsOnBridge = true
print("BRIDGE CONTACT")
} else if other.categoryBitMask == waterMask {
print("WATER CONTACT")
}
}
func didEnd(_ contact: SKPhysicsContact) {
let bitmaskA = contact.bodyA.categoryBitMask
let bitmaskB = contact.bodyB.categoryBitMask
if bitmaskA == bridgeMask || bitmaskB == bridgeMask {
playerIsOnBridge = false
}
}

Swift SpriteKit Collisions Registered Multiple Times

I'm using SpriteKit and Swift to build an iPhone game, and my collision detection system is not functioning as I want it to. When my "bullet" physics body and my "player" physics body collide, the collision detection function is being called multiple times, usually 4-12 times. I have tried setting "usesPreciseCollisionDetection" to true, but it is still problematic. Also, it seems the method is called more times when the bullet hits the player at an angle rather than straight on. Any thoughts how to fix this?
Collision Types:
enum ColliderType:UInt32 {
case Player = 0b1
case Bullet = 0b10
}
Player Physics Body Settings:
playerBody!.categoryBitMask = ColliderType.Player.rawValue
playerBody!.contactTestBitMask = ColliderType.Bullet.rawValue
playerBody!.collisionBitMask = ColliderType.Bullet.rawValue
Bullet Physics Body Settings:
bulletBody!.categoryBitMask = ColliderType.Bullet.rawValue
bulletBody!.contactTestBitMask = ColliderType.Player.rawValue
bulletBody!.collisionBitMask = ColliderType.Player.rawValue
Collision Detection Method:
func didBeginContact(contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == 0b1) && (contact.bodyB.categoryBitMask == 0b10) {
playerVbullet(contact.bodyA, bullet: contact.bodyB)
}
if (contact.bodyA.categoryBitMask == 0b10) && (contact.bodyB.categoryBitMask == 0b11) {
playerVbullet(contact.bodyB, bullet: contact.bodyA)
}
}
Function Called on Collision:
func playerVbullet(player:SKPhysicsBody, bullet:SKPhysicsBody) {
bullet.node?.removeFromParent()
collisions++
println(collisions)
}
Give your bullet node a name:
let bullet = SKSPriteNode()
bullet.name = "bullet"
Then check your physics contact
if (contact.bodyA.node?.name == "bullet") {
contact.bodyA.node?.removeFromParent()
} else if contact.bodyB.node?.name == "bullet" {
contact.bodyB.node?.removeFromParent()
}
Good luck!

Why my node calls didBeginContact method when its not in the Scene

func didBeginContact(contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask == PhysicsCategory.overPow || contact.bodyB.categoryBitMask == PhysicsCategory.overPow{
let sk = delegateForCollision!.view as! SKView
let newScene = GG(fileNamed: "GG")
newScene!.delegateFor = delegateForCollision
newScene?.scaleMode = .AspectFill
sk.presentScene(newScene)
}
if contact.bodyA.categoryBitMask == PhysicsCategory.glem && contact.bodyB.categoryBitMask == PhysicsCategory.kappa{
contact.bodyA.node?.removeFromParent()
glem++
glemLabel.text = "SKAŁY: \(glem)"
}
if contact.bodyB.categoryBitMask == PhysicsCategory.glem && contact.bodyA.categoryBitMask == PhysicsCategory.kappa{
contact.bodyB.node?.removeFromParent()
glem++
glemLabel.text = "SKAŁY: \(glem)"
}
}
glem and kappa categoryBitMask nodes are colliding so glem variable should be ++ one time then node is removed from scene but it looks like this method is called more times during next frames. I see it in logs because I added print("\(glem)") in glem didSet. Why does it happen?
I changed glem++ to if contact.bodyB.node?.parent != nil{glem++}
and now it works as it should.

The proper way of using didBeginContact in SpriteKit games - Swift

I have 3 sprites which can collide with each other and have contactTestBitMask and categoryBitMask set.
I had two sprites which used didBeginContact method to see if they have collided and it worked fine, but now I am not sure how to set it to check contacts of multiple objects and run the function which is different depending on which two bodies collide.
My PhysicsCategory:
struct PhysicsCategory {
static let None: UInt32 = 0
static let All: UInt32 = UInt32.max
static let Bird: UInt32 = 0b1
static let Cloud: UInt32 = 0b10
static let Desk: UInt32 = 0b100
static let Star: UInt32 = 0b101
static let StarSpecial: UInt32 = 0b110
}
The didBeginContact method in GameScene:
func didBeginContact(contact: SKPhysicsContact) {
var BirdBody: SKPhysicsBody?
var DeskBody: SKPhysicsBody?
var SpecialStarBody: SKPhysicsBody?
//var SpecialStarBody: SKPhysicsBody
if contact.bodyA.categoryBitMask == PhysicsCategory.Bird {
BirdBody = contact.bodyA
DeskBody = contact.bodyB
} else if contact.bodyA.categoryBitMask == PhysicsCategory.Desk {
BirdBody = contact.bodyB
DeskBody = contact.bodyA
} else if contact.bodyA.categoryBitMask == PhysicsCategory.StarSpecial {
SpecialStarBody = contact.bodyA
}
if (DeskBody != nil) {
birdSprite.BirdDidCollideWithDesk(BirdBody?.node as! Bird, desk: DeskBody?.node as! Desk, scoreClass: scoreClass, scoreLabel: scoreLabel)
}
}
What I want to do is check if the bird came in contact with a desk and in this case, it should run the function for the bird and the desk, otherwise I want to see whether bird came in contact with a SpecialStar, I haven't written a function for what to do in this case, but later on, I would call a different function for this case. I am also adding some additional sprites, so I would be grateful if anyone could explain how this should be done for code to be well written and not cause any errors.
You can check if bird contacted with desk
if ((contact.bodyA.categoryBitMask == PhysicsCategory.Bird && contact.bodyB.categoryBitMask == PhysicsCategory.Desk) ||
(contact.bodyA.categoryBitMask == PhysicsCategory.Desk && contact.bodyB.categoryBitMask == PhysicsCategory.Bird)) {
print("Bird, desk")
// Handle contact bird with desk
}
Bird contact with starSpecial
if ((contact.bodyA.categoryBitMask == PhysicsCategory.Bird && contact.bodyB.categoryBitMask == PhysicsCategory.StarSpecial) ||
(contact.bodyA.categoryBitMask == PhysicsCategory.Desk && contact.bodyB.categoryBitMask == PhysicsCategory.StarSpecial)) {
print("Bird, StarSpecial")
// Handle contact bird with StarSpecial
}
Just a note: Variables should start with a lowercase letter.
To keep code clear I recommend to create class file for every node.
import Foundation
import SpriteKit
class Monster: SKSpriteNode {
init(world: SKNode) {
super.init(texture: SKTexture(imageNamed: "MonsterImageName"), color: UIColor.clearColor(), size: CGSizeMake(world.frame.size.width / 18, world.frame.size.width / 36))
position = CGPointMake(world.frame.size.width / 2, world.frame.size.height / 2)
zPosition = 100
// etc
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
And add it like this
var monster = Monster.init(world)
world.addChild(monster)