Specific Head On Collision in Swift 4 - swift

I am new to iOS development and I made an infinite runner game. As you can see in the function below, the player dies when it collides with an obstacle. However, the player dies whenever it collides with any side of the obstacle. How can I limit this collision detection to a specific side of the frame of the obstacle?
func didBegin(_ contact: SKPhysicsContact) { //so the player can't jump while in the air
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.node?.name == "Player" {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.node?.name == "Player" && secondBody.node?.name == "Ground" { //if colliding with ground
canJump = true //can jump when on ground
}
if firstBody.node?.name == "Player" && secondBody.node?.name == "Bus" || firstBody.node?.name == "Player" && secondBody.node?.name == "Obstacle" {
// kill player and prompt buttons
playerDied()
}
}

You may try to calculate the intersection between two colliding nodes, then just checking width and height of the resulting frame should be enough to detect the collision side, a rough explanation:
collision left/right
collision top/down
for a infinite runner game this check should be enough:
if firstBody.node?.name == "Player" && secondBody.node?.name == "Obstacle" {
let intersection = firstBody.node!.frame.intersection(secondBody.node!.frame)
if intersection.height > intersection.width { // collision left/right
playerDied()
} else { // collision top/down
//...//
}
}

Related

SKPhysicsContact isnt removing enemy after contact

My bullet is finally being removed after touching the enemy however the enemy isnt being removed. Is something wrong with my physicscontact code? My player is also now going out of the screen border but i just fixed that by removing both bodyB and bodyA nil lines. I dont know if thats the best way to fix the 2nd problem and if it will mess up my enemy code in the future.
func didBegin(_ contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == bulletCategory) {
contact.bodyA.node?.physicsBody?.collisionBitMask = 0
contact.bodyA.node?.physicsBody?.categoryBitMask = 0
} else if (contact.bodyB.categoryBitMask == bulletCategory) {
contact.bodyB.node?.physicsBody?.collisionBitMask = 0
contact.bodyB.node?.physicsBody?.categoryBitMask = 0
}
if contact.bodyA.categoryBitMask == enemyCategory {
contact.bodyB.node?.removeFromParent()
contact.bodyB.node?.physicsBody = nil
contact.bodyB.node?.removeAllActions()
} else if contact.bodyB.categoryBitMask == enemyCategory {
contact.bodyA.node?.removeFromParent()
contact.bodyA.node?.physicsBody = nil
contact.bodyA.node?.removeAllActions()
}
}

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
}
}

Why is my didBeginContact function detecting way too many collisions?

My didBeginContact function is detecting about 60 collisions between two SKSpriteNodes when there should only be one.
func didBeginContact(contact: SKPhysicsContact) {
let firstBody = contact.bodyA
let secondBody = contact.bodyB
if firstBody.categoryBitMask == bulletCategory && secondBody.categoryBitMask == dragonCategory || firstBody.categoryBitMask == dragonCategory && secondBody.categoryBitMask == bulletCategory{
print("collision happened")
}
}
When the nodes come into contact the console prints "collision happened" many many times.
Here is how i declare physics bodys for each SKSpriteNode
dragonNode.physicsBody = SKPhysicsBody(texture: dragonNode.texture!, size: CGSizeMake(dragonNode.size.width, dragonNode.size.height))
dragonNode.physicsBody?.affectedByGravity = false
dragonNode.physicsBody?.dynamic = true
dragonNode.physicsBody?.categoryBitMask = dragonCategory
dragonNode.physicsBody?.collisionBitMask = bulletCategory
dragonNode.physicsBody?.contactTestBitMask = bulletCategory
bulletNode.physicsBody = SKPhysicsBody(texture: texture, size: texture.size())
bulletNode.physicsBody?.affectedByGravity = false
bulletNode.physicsBody?.dynamic = true
bulletNode.physicsBody?.categoryBitMask = bulletCategory
bulletNode.physicsBody?.collisionBitMask = dragonCategory
bulletNode.physicsBody?.contactTestBitMask = dragonCategory
This is one of the last things i need to fix for my game to be completed so if anyone can help that would be great!
It's because theoretically your game is running at 60 frames per second. So every 60th of a second it is detecting the collision and printing the warning. You haven't put any code into say stop detecting this collision. You could always put a flag on the object
dragonNode.collided = true
and then detect for the collision and the flag
if (firstBody.categoryBitMask == bulletCategory && secondBody.categoryBitMask == dragonCategory || firstBody.categoryBitMask == dragonCategory && secondBody.categoryBitMask == bulletCategory) && dragonNode.collided != true {
dragonNode.collided = true
print("collision happened")
}
this way the collision only fires once

Having problems calling functions in swift

This function should increase my snake size by increment width when I call in my didbegincontact function. However when contact is made it calls the function once and then never calls it again. I am not sure why when contact is made it does not keep increasing my snake size by increment
func increaseSnakeSize(increment: CGFloat){
snake.snake1.size = CGSizeMake(snake.size.width + increment, snake.size.height + increment)
snake.snake2.size = CGSizeMake(snake.size.width + increment, snake.size.height + increment)
snake.snake3.size = CGSizeMake(snake.size.width + increment, snake.size.height + increment)
print(snake.snake1.size)
}
// didBeginContact
if (firstBody.categoryBitMask & physicsCategory.snakeCategory == 0b1) && (secondBody.categoryBitMask & physicsCategory.foodCategory == 0b10 ){
score++
scoreLabel.text = "\(score)"
food.removeFromParent()
addFood()
increaseSnakeSize(2)
}
When the initial contact is made, the snake grows to 22x22, but its physics body's size stays at 20x20. A solution is to create a new physics body that's 22x22 for the initial contact, 24x24 for the next, 26x26 for the contact after that, ... For example,
func increaseSnakeSize (increment: CGFloat) {
snake.snake1.size = CGSizeMake(snake.size.width + increment, snake.size.height + increment)
// Create a new, larger physics body that matches the size of the snake
snake.snake1.physicsBody = SKPhysicsBody(circleOfRadius:snake.size.width/2.0)
// Configure the physics body's property accordingly
snake.snake1.physicsBody?.affectedByGravity = false
...
}
Another potential issue is the order of contact.bodyA and contact.bodyB can switch between contacts. You will need to check if the snake is the first body and the food is the second and the food is the first body and the snake is the second body. Here's an example
func didBeginContact (contact: SKPhysicsContact) {
var firstBody, 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 == physicsCategory.snakeCategory) && (secondBody.categoryBitMask == physicsCategory.foodCategory ) {
// Increase size of the snake
}
or
let bitMask = contact.BodyA.categoryBitMask | contact.BodyB.categoryBitMask
if bitMask == physicsCategory.snakeCategory | physicsCategory.foodCategory {
// Increase size of the snake
}
Looks like you do not increase the PhysicsBody of your snake. Do you have physics hit boxes showing in your app? If not, I would recommend turning them on and seeing how it behaves. In your View code, do:self.showsPhysics = true

SpriteKit - Make a sprite move similar t another sprite

I'm making a type of a platformer ( think super mario but in a top-down view style ) game and i want my main character to move with the platform it has contact with.
So i used this:
-(void)didBeginContact:(SKPhysicsContact *)contact
{
SKPhysicsBody *firstBody;
SKPhysicsBody *secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
firstBody = contact.bodyA;
secondBody = contact.bodyB;
}
else {
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
if (firstBody.categoryBitMask == PlatformCategory || secondBody.categoryBitMask == PlayerCategory) {
_contact = YES;
}
-(void)didSimulatePhysics
{
if (_contact) {
_player.position = CGPointMake(_platform2.position.x, _platform2.position.y + 10);
}
}
}
It kinda worked, and now my player is moving with that SPECIFIC platform when it touches it, but that's not a very practical way for doing it because i will be randomly generating platforms. So how t achieve that ?
SKPhysicsBody has a property called node, which is the parent sprite it's attached to. In your collision method, test if the physics body is of collision category platform, then:
SKSpriteNode *thisCollidedPlatform = (SKSpriteNode*) nameOfPhysicsBody.node
And then use the position of thisCollidedPlatform to set the player position.