import SpriteKit
// fix spawning so close to the middle
// get ball col working
// set width apart/ height they must be apart (if statement)
let BallCategoryName = "ball"
let BarCategoryName = "block"
let BarNodeCategoryName = "blockNode"
let GreenBallCategory : UInt32 = 0x1 << 0
let RedBallCategory: UInt32 = 0x1 << 1
let GreenBarCategory : UInt32 = 0x1 << 2
let RedBarCategory : UInt32 = 0x1 << 3
class GameScene: SKScene, SKPhysicsContactDelegate {
//VARIABLES IMPORTANTE//
var greenBall = SKSpriteNode(imageNamed: "greenball")
var redBall = SKSpriteNode(imageNamed: "redball")
var bar0 = SKSpriteNode(imageNamed: "bar0")
var bar1 = SKSpriteNode(imageNamed: "bar1")
var bar2 = SKSpriteNode(imageNamed: "bar2")
var bar3 = SKSpriteNode(imageNamed: "bar3")
var bar4 = SKSpriteNode(imageNamed: "bar4")
var bar5 = SKSpriteNode(imageNamed: "bar5")
override func didMoveToView(view: SKView) {
physicsWorld.contactDelegate = self
// BALL CHARACTERISTICS//
//Green//
greenBall.position = CGPoint(x: frame.size.width*0.25, y: (frame.size.height * 0.95)/2)
greenBall.anchorPoint = CGPoint(x: 0.5, y: 0.5)
greenBall.physicsBody = SKPhysicsBody(circleOfRadius: greenBall.size.width/2)
greenBall.physicsBody?.friction = 0
greenBall.physicsBody?.restitution = 1
greenBall.physicsBody?.linearDamping = 0
greenBall.physicsBody?.angularDamping = 0
greenBall.physicsBody?.affectedByGravity = false
greenBall.name = BallCategoryName
addChild(greenBall)
//Red//
redBall.anchorPoint = CGPoint(x: 0.5 , y: 0.5)
redBall.position = CGPoint(x: frame.size.width*0.75 , y: (frame.size.height * 0.95)/2)
redBall.physicsBody = SKPhysicsBody(circleOfRadius: greenBall.size.width/2)
redBall.physicsBody?.friction = 0
redBall.physicsBody?.restitution = 1
redBall.physicsBody?.linearDamping = 0
redBall.physicsBody?.angularDamping = 0
redBall.physicsBody?.affectedByGravity = false
redBall.physicsBody?.dynamic = false
addChild(redBall)
//////////////////////////////////////////////////////
// SETTING UP SCENE//
GameScene(size: self.view!.frame.size) //WHy not work
let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody = borderBody
self.physicsBody?.friction = 0
// BACKGROUND COLOR
// PHYSICS //
physicsWorld.gravity = CGVectorMake(0, 0)
//////////////////////////////////////////////////////
// EXTRA BARS
var midBar = SKShapeNode(rectOfSize: CGSize(width : frame.size.width, height: 3))
var menuBar = SKShapeNode(rectOfSize: CGSize(width : frame.size.width, height: 3))
var invisMenuBar = SKShapeNode(rectOfSize: CGSize(width: frame.size.width, height: 0.00001))
var botBar = SKShapeNode(rectOfSize: CGSize(width : frame.size.width, height: 3))
midBar.fillColor = SKColor.whiteColor()
menuBar.fillColor = SKColor.whiteColor()
invisMenuBar.fillColor = SKColor.purpleColor()
botBar.fillColor = SKColor.whiteColor()
////MID BAR////
var minus = frame.size.height * 0.049
midBar.position = CGPoint(x: frame.size.width/2, y: (frame.size.height * 0.95)/2)
addChild(midBar)
////BOT BAR////
botBar.position = CGPoint(x: frame.size.width/2, y: 0 + (botBar.frame.size.height/2))
addChild(botBar)
////MENU BAR////
menuBar.position = CGPoint(x: frame.size.width/2, y: frame.size.height - (frame.size.height * 0.05))
addChild(menuBar)
//// INVIS MENU BAR ////
invisMenuBar.position = CGPoint(x: frame.size.width/2, y: frame.size.height - (frame.size.height * 0.047))
invisMenuBar.physicsBody = SKPhysicsBody(rectangleOfSize: invisMenuBar.frame.size)
invisMenuBar.physicsBody?.friction = 0
invisMenuBar.physicsBody?.restitution = 1
invisMenuBar.physicsBody?.linearDamping = 0
invisMenuBar.physicsBody?.angularDamping = 0
invisMenuBar.physicsBody?.affectedByGravity = false
invisMenuBar.physicsBody?.dynamic = false
invisMenuBar.zPosition = 100
menuBar.zPosition = 5
addChild(invisMenuBar)
// TEST STUFF WITH BARS //
let chosenOne = SKSpriteNode(imageNamed: "bar4")
chosenOne.position = CGPoint(x: frame.midX - chosenOne.frame.width/2 - 50 , y: self.frame.height * 0.75)
addChild(chosenOne)
//////////////////////////////////////////////////////
//// SETTING UP MY CONTACT ///
greenBall.physicsBody?.categoryBitMask = GreenBallCategory
chosenOne.physicsBody?.categoryBitMask = RedBarCategory
greenBall.physicsBody?.contactTestBitMask = RedBarCategory
chosenOne.physicsBody?.contactTestBitMask = GreenBallCategory
chosenOne.physicsBody = SKPhysicsBody(rectangleOfSize: chosenOne.frame.size)
func didBeginContact(contact: SKPhysicsContact) {
// 1. Create local variables for two physics bodies
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
// 2. Assign the two physics bodies so that the one with the lower category is always stored in firstBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
// 3. react to the contact between ball and bottom
if firstBody.categoryBitMask == GreenBallCategory && secondBody.categoryBitMask == RedBarCategory {
//TODO: Replace the log statement with display of Game Over Scene
println("Hit bottom. First contact has been made.")
}
}
I'm following http://www.raywenderlich.com/84341/create-breakout-game-sprite-kit-swift to the letter. I've got the self contact delegate all set up, the two do hit each other but it doesn't print to the logs to prove the collision stuff is actually working.
Any ideas?
Your didBeginContact method is inside the didMoveToView method. Since both methods in SKPhysicsContactDelegate are optional:
protocol SKPhysicsContactDelegate : NSObjectProtocol {
optional func didBeginContact(contact: SKPhysicsContact)
optional func didEndContact(contact: SKPhysicsContact)
}
you're not being warned that GameScene doesn't implement the methods.
Move didBeginContact out of didMoveToView and you should be fine.
(On a side note: I would advise that you split up didMoveToView into several, smaller methods. It'll make it easier to understand what's going on because, at the moment, it looks pretty bloated.)
Related
I'm a beginner in game development in Xcode and my player keeps falling through the ground that I added on the GameScene.
In the GameScene I only added the ground as an SKTexture and a player, which is also an SKTexture. There's also a physicsCategories structure.
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
struct physicsCategories {
static let None: UInt32 = 0
static let Player: UInt32 = 0b1
static let Ground: UInt32 = 0b100
}
override func didMove(to view: SKView) {
self.backgroundColor = UIColor.blue
self.anchorPoint = CGPoint(x: 0.0, y: 0.0)
self.physicsWorld.contactDelegate = self
self.physicsWorld.gravity = CGVector(dx: 0, dy: -2)
let player = Player(scene: self)
player.physicsBody = SKPhysicsBody(rectangleOf: player.size)
player.physicsBody?.categoryBitMask = physicsCategories.Player
player.physicsBody?.contactTestBitMask = physicsCategories.Ground
player.physicsBody?.collisionBitMask = physicsCategories.Ground
player.physicsBody?.affectedByGravity = true
player.physicsBody?.isDynamic = true
addChild(player)
createGrounds()
}
func didBegin(_ contact: SKPhysicsContact) {
var body1 = SKPhysicsBody()
var body2 = SKPhysicsBody()
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
body1 = contact.bodyA
body2 = contact.bodyB
} else {
body1 = contact.bodyB
body2 = contact.bodyA
}
if (body1.categoryBitMask == physicsCategories.Player && body2.categoryBitMask == physicsCategories.Ground) {
body1.node?.position.y = 80
}
}
func createGrounds() {
let backgroundTexture = SKTexture(imageNamed: "ground")
for i in 0 ... 3 {
let background = SKSpriteNode(texture: backgroundTexture)
background.zPosition = 2
background.anchorPoint = CGPoint(x: 0.0, y: 0.0)
background.size = CGSize(width: (self.scene?.size.width)!, height: 250)
background.position = CGPoint(x: (backgroundTexture.size().width * CGFloat(i)), y: -(self.frame.size.height/2))
background.physicsBody = SKPhysicsBody(rectangleOf: background.size)
background.physicsBod
background.physicsBody?.isDynamic = false
background.physicsBody!.affectedByGravity = false
background.physicsBody?.categoryBitMask = physicsCategories.Ground
background.physicsBody?.contactTestBitMask = physicsCategories.Player
background.physicsBody?.collisionBitMask = physicsCategories.Player
background.physicsBody?.applyForce(CGVector(dx: 0, dy: 2))
addChild(background)
let moveLeft = SKAction.moveBy(x: -backgroundTexture.size().width, y: 0, duration: 4)
let moveReset = SKAction.moveBy(x: backgroundTexture.size().width , y: 0, duration: 0)
let moveLoop = SKAction.sequence([moveLeft, moveReset])
let moveForever = SKAction.repeatForever(moveLoop)
background.run(moveForever)
}
}
}
I am making a little FlappyBird clone and have got everything working as it should until I changed the physics body of the bird to be exact to the texture. Now what it does is when it flies through the gap in the pipes it counts 30 points instead of just 1 point.
This only happens when I use the texture exact physics body which I need because the bird isn't round nor rectangular.
How would I go about making the collision so it only collides once with each gap node. I have tried setting the categoryBitBask to 0 after the contact but then all the gaps after don't add to the point count anymore at all.
Here is the full game code:
var score = 0
class GameScene: SKScene, SKPhysicsContactDelegate {
var bird = SKSpriteNode()
var bg = SKSpriteNode()
var ground = SKSpriteNode()
var scoreLabel = SKLabelNode(fontNamed: "Candice")
var gameOverLabel = SKLabelNode(fontNamed: "Candice")
var countbg = SKSpriteNode()
var timer = Timer()
enum ColliderType: UInt32 {
case Bird = 1
case Object = 2
case Gap = 4
}
var gameOver = false
let swooshSound = SKAction.playSoundFileNamed("sfx_swooshing.wav", waitForCompletion: false)
let pointSound = SKAction.playSoundFileNamed("sfx_point.wav", waitForCompletion: false)
let hitSound = SKAction.playSoundFileNamed("sfx_hit.wav", waitForCompletion: false)
#objc func makePipes() {
let movePipes = SKAction.move(by: CGVector(dx: -2 * self.frame.width, dy: 0), duration: TimeInterval(self.frame.width / 150))
let removePipes = SKAction.removeFromParent()
let moveAndRemovePipes = SKAction.sequence([movePipes, removePipes])
let gapHeight = bird.size.height * 2.8
let movementAmount = arc4random() % UInt32(self.frame.height) / 2
let pipeOffset = CGFloat(movementAmount) - self.frame.height / 4
let pipeTexture = SKTexture(imageNamed: "pipe1.png")
let pipe1 = SKSpriteNode(texture: pipeTexture)
pipe1.position = CGPoint(x: self.frame.midX + self.frame.width, y: self.frame.midY + pipeTexture.size().height / 2 + gapHeight / 2 + pipeOffset)
pipe1.zPosition = 2
pipe1.run(moveAndRemovePipes)
pipe1.physicsBody = SKPhysicsBody(rectangleOf: pipeTexture.size())
pipe1.physicsBody!.isDynamic = false
pipe1.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
pipe1.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
pipe1.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
self.addChild(pipe1)
let pipe2Texture = SKTexture(imageNamed: "pipe2.png")
let pipe2 = SKSpriteNode(texture: pipe2Texture)
pipe2.position = CGPoint(x: self.frame.midX + self.frame.width, y: self.frame.midY - pipeTexture.size().height / 2 - gapHeight / 2 + pipeOffset)
pipe2.zPosition = 2
pipe2.run(moveAndRemovePipes)
pipe2.physicsBody = SKPhysicsBody(rectangleOf: pipe2Texture.size())
pipe2.physicsBody!.isDynamic = false
pipe2.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
pipe2.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
pipe2.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
self.addChild(pipe2)
let gap = SKNode()
gap.position = CGPoint(x: self.frame.midX + self.frame.width, y: self.frame.midY + pipeOffset)
gap.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 1, height: gapHeight))
gap.physicsBody!.isDynamic = false
gap.run(moveAndRemovePipes)
gap.physicsBody!.contactTestBitMask = ColliderType.Bird.rawValue
gap.physicsBody!.categoryBitMask = ColliderType.Gap.rawValue
gap.physicsBody!.collisionBitMask = ColliderType.Gap.rawValue
self.addChild(gap)
}
func didBegin(_ contact: SKPhysicsContact) {
if gameOver == false {
if contact.bodyA.categoryBitMask == ColliderType.Gap.rawValue || contact.bodyB.categoryBitMask == ColliderType.Gap.rawValue {
score += 1
scoreLabel.text = String(format: "%05d", score)
run(pointSound)
} else {
self.speed = 0
run(hitSound)
gameOver = true
timer.invalidate()
bird.removeFromParent()
let changeSceneAction = SKAction.run(changeScene)
self.run(changeSceneAction)
}
}
}
//MARK: Change to Game Over Scene
func changeScene(){
let sceneToMoveTo = GameOverScene(size: self.size)
sceneToMoveTo.scaleMode = self.scaleMode
let myTransition = SKTransition.fade(withDuration: 0.5)
self.view!.presentScene(sceneToMoveTo, transition: myTransition)
}
override func didMove(to view: SKView) {
self.physicsWorld.contactDelegate = self
setupGame()
}
func setupGame() {
timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.makePipes), userInfo: nil, repeats: true)
let groundTexture = SKTexture(imageNamed: "ground.png")
let moveGroundAnimation = SKAction.move(by: CGVector(dx: -groundTexture.size().width, dy: 0), duration: 7)
let shiftGroundAnimation = SKAction.move(by: CGVector(dx: groundTexture.size().width, dy: 0), duration: 0)
let moveGroundForever = SKAction.repeatForever(SKAction.sequence([moveGroundAnimation, shiftGroundAnimation]))
var i: CGFloat = 0
while i < 3 {
ground = SKSpriteNode(texture: groundTexture)
ground.position = CGPoint(x: self.size.width * i, y: self.size.height / 7.65)
ground.zPosition = 3
ground.run(moveGroundForever)
self.addChild(ground)
i += 1
}
let bottom = SKNode()
bottom.position = CGPoint(x: self.frame.midX, y: self.size.height / 7)
bottom.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.frame.width, height: 1))
bottom.physicsBody!.isDynamic = false
bottom.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
bottom.physicsBody!.categoryBitMask = ColliderType.Object.rawValue
bottom.physicsBody!.collisionBitMask = ColliderType.Object.rawValue
self.addChild(bottom)
let bgTexture = SKTexture(imageNamed: "bg.png")
bg = SKSpriteNode(texture: bgTexture)
bg.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
bg.size = self.frame.size
bg.zPosition = 1
self.addChild(bg)
let birdTexture = SKTexture(imageNamed: "flappy1.png")
let bird2Texture = SKTexture(imageNamed: "flappy2.png")
let bird3Texture = SKTexture(imageNamed: "flappy3.png")
let bird4Texture = SKTexture(imageNamed: "flappy4.png")
let bird5Texture = SKTexture(imageNamed: "flappy5.png")
let bird6Texture = SKTexture(imageNamed: "flappy6.png")
let animation = SKAction.animate(with: [birdTexture, bird2Texture, bird3Texture, bird4Texture, bird5Texture, bird6Texture], timePerFrame: 0.1)
let makeBirdFlap = SKAction.repeatForever(animation)
bird = SKSpriteNode(texture: birdTexture)
bird.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
bird.setScale(1)
bird.zPosition = 6
bird.run(makeBirdFlap)
self.addChild(bird)
bird.physicsBody = SKPhysicsBody.init(circleOfRadius: birdTexture.size().height / 2)
//bird.physicsBody = SKPhysicsBody(texture: birdTexture, size: birdTexture.size())
bird.physicsBody!.isDynamic = false
bird.physicsBody!.contactTestBitMask = ColliderType.Object.rawValue
bird.physicsBody!.categoryBitMask = ColliderType.Bird.rawValue
bird.physicsBody!.collisionBitMask = ColliderType.Bird.rawValue
let countbg = SKSpriteNode(imageNamed: "count_bg.png")
countbg.position = CGPoint(x: self.size.width / 4.8, y: self.size.height * 0.94)
countbg.setScale(0.8)
countbg.zPosition = 4
addChild(countbg)
scoreLabel.fontSize = 80
scoreLabel.text = String(format: "%05d", score)
scoreLabel.fontColor = SKColor(red: 218/255, green: 115/255, blue: 76/255, alpha: 1)
scoreLabel.position = CGPoint(x: self.size.width / 4, y: self.size.height * 0.94)
scoreLabel.zPosition = 5
addChild(scoreLabel)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if gameOver == false {
bird.physicsBody!.isDynamic = true
bird.physicsBody!.velocity = CGVector(dx: 0, dy: 0)
bird.physicsBody!.applyImpulse(CGVector(dx: 0, dy: 280))
//run(swooshSound)
} else {
gameOver = false
score = 0
self.speed = 1
self.removeAllChildren()
setupGame()
}
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
If you would be using RxSwift, you would be able to easily get rid of those extra events easily by using debounce() or throttle() or distinctUntilChanged(). If you are willing to try this approach, give RxSpriteKit framework a go. Otherwise, store a timestamp of the last contact and ignore the following contacts until some time period elapses.
I'm getting some difficulty detecting collision in my SpriteKit Game. I simply want to detect collision between the missiles and the enemies and boats.
I have the ColliderType:
struct ColliderType {
static let Boat: UInt32 = 1
static let Enemy: UInt32 = 2
static let Wall: UInt32 = 3
static let Bullet: UInt32 = 4
}
class GameplayScene: SKScene, SKPhysicsContactDelegate {
var player = SKSpriteNode()
var enemy = SKSpriteNode()
var boat = SKSpriteNode()
var missile = SKSpriteNode()
The didBegin contact:
func didBegin(_ contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.node?.name == "Missile" {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.node?.name == "Missile" && secondBody.node?.name ==
"Enemy" {
incrementScore()
secondBody.node?.removeFromParent()
} else if firstBody.node?.name == "Missile" &&
secondBody.node?.name == "Boat" {
incrementScore()
}
}
I have added the "physicsWorld.contactDelegate = self" in the didMove toview
I have also added physicsBodies to all the relevant spritenodes:
func fireMissile() {
let missile = SKSpriteNode(color: .yellow, size: CGSize(width: 20,
height: 5))
missile.name = "Missile"
missile.position = CGPoint(x: player.position.x + 28, y:
player.position.y + 10)
missile.zPosition = 2
missile.physicsBody = SKPhysicsBody(rectangleOf: missile.size)
missile.physicsBody?.isDynamic = false
missile.physicsBody?.categoryBitMask = ColliderType.Bullet
missile.physicsBody?.collisionBitMask = ColliderType.Enemy |
ColliderType.Boat
missile.physicsBody?.contactTestBitMask = ColliderType.Enemy |
ColliderType.Boat
self.addChild(missile)
}
func createEnemies() {
let enemy = SKSpriteNode(imageNamed: "Enemy1")
enemy.name = "Enemy"
enemy.anchorPoint = CGPoint(x: 0.5, y: 0.5)
enemy.physicsBody = SKPhysicsBody(circleOfRadius: enemy.size.height
/ 2)
enemy.physicsBody?.categoryBitMask = ColliderType.Enemy
enemy.physicsBody?.affectedByGravity = false
enemy.physicsBody?.isDynamic = false
enemy.zPosition = 3
enemy.position.y = self.frame.height + 100
enemy.position.x = CGFloat.randomBetweenNumbers(firstNum: -347.5,
secondNum: -85)
self.addChild(enemy)
}
func createBoat() {
let boat = SKSpriteNode(imageNamed: "Boat")
boat.name = "Boat"
boat.anchorPoint = CGPoint(x: 0.5, y: 0.5)
boat.physicsBody = SKPhysicsBody(circleOfRadius: boat.size.height /
2)
boat.physicsBody?.categoryBitMask = ColliderType.Boat
boat.physicsBody?.affectedByGravity = false
boat.physicsBody?.isDynamic = false
boat.zPosition = 3
boat.position.y = self.frame.height + 100
boat.position.x = CGFloat.randomBetweenNumbers(firstNum: 0,
secondNum: 0)
self.addChild(boat)
}
Firstly, some of your categories are wrong:
static let Wall: UInt32 = 3
static let Bullet: UInt32 = 4
This effectively defines Wall as being both a Boat and an Enemy. Change them to:
static let Wall: UInt32 = 4
static let Bullet: UInt32 = 8
(Categories should always be unique powers of 2 - 1, 2, 4, 8, 16 etc).
The rest looks ok, so try that and let us know if it’s working.
Edit:
OK - just noticed that all of your physics bodies have their isDynamic property set to false - this means that, among other things, the body will not trigger contacts. so if you want missile to generate contacts with either enemy or boat, then either missile should be dynamic or both enemy and boat should be dynamic (only 1 of the 2 objects involved in a contact needs to by dynamic).
I have a 40x40 rectangle node, and I want to detect when the bottom touches a platform.
I tried this
let feet = SKPhysicsBody(rectangleOfSize: CGSize(width: hero.frame.size.width, height: 1), center: CGPoint(x: 0, y: -(hero.frame.size.height/2 - 0.5)))
then set the categoryBitMask, collisionBitMask, contactTestBitMaskand added it to the hero
hero.physicsBody = SKPhysicsBody(bodies: [feet])
But in didBeginContact the println() doesn't print.
I need a body for the bottom of the rectangle and one for the top, because if hero hits a platform from below the collision should push him down.
Update
Here is how I set the bit masks
let heroFeetCategory: UInt32 = 1 << 0
let edgeCategory: UInt32 = 1 << 1
let groundCategory: UInt32 = 1 << 2
let feet = SKPhysicsBody(rectangleOfSize: CGSize(width: hero.frame.size.width, height: 10), center: CGPoint(x: 0, y: -(hero.frame.size.height/2 - 5)))
feet.collisionBitMask = edgeCategory | groundCategory
feet.contactTestBitMask = groundCategory
feet.categoryBitMask = heroFeetCategory
hero.physicsBody = SKPhysicsBody(bodies: [feet])
hero.physicsBody?.usesPreciseCollisionDetection = true
hero.physicsBody?.velocity = CGVectorMake(0, 0)
hero.physicsBody?.restitution = 0.0
hero.physicsBody?.friction = 0.0
hero.physicsBody?.angularDamping = 0.0
hero.physicsBody?.linearDamping = 1.0
hero.physicsBody?.allowsRotation = false
hero.physicsBody?.mass = 0.0641777738928795
world.addChild(hero)
and for the ground
let ground = SKSpriteNode(color: UIColor.whiteColor(), size: CGSizeMake(38, 38))
ground.name = "groundName"
ground.position = CGPoint(x: 0, y: -(self.frame.size.height/2 - ground.frame.size.height/2))
ground.physicsBody = SKPhysicsBody(rectangleOfSize: ground.size)
ground.physicsBody?.collisionBitMask = edgeCategory | heroFeetCategory
ground.physicsBody?.contactTestBitMask = heroFeetCategory
ground.physicsBody?.categoryBitMask = groundCategory
world.addChild(ground)
And how I detect if they touch
func didBeginContact(contact: SKPhysicsContact) {
var notTheHero: SKPhysicsBody!;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
notTheHero = contact.bodyB;
} else {
notTheHero = contact.bodyA;
}
println(notTheHero.node) // print "heroName"
if (notTheHero.categoryBitMask == groundCategory) {
println("touch began?"); // is never called
}
}
collision is fine, but when you print the node's name through the physics body with notTheHero.node you only access the SKNode, and not the NSString property of its name. Instead, try something like println(notTheHero.node.name);
I can’t find any help or solution for my problem. I have 4 SKSpriteNodes named: bottomGoalGreen, topGoalGreen, bottomGoalBlue, and topGoalBlue. I also have a ball that is a SKSpriteNode named ball. My first question/problem is when I have my ball collide with, for example, topGoalGreen or bottomGoalGreen, I want the topGoalGreen to be removed as well as bottomGoalGreen and then topGoalBlue and bottomGoalBlue to appear and vice versa. My other problem is with my ball and the collision. I have two SKAction.moveToY so the ball can move up and down the screen. I was wondering if the SKActions could be the culprit to why the collision will not happen. I hope I improved my question. If not, I will try again to clarify.
import Foundation
import SpriteKit
import UIKit
struct PhysicsCatagory {
static let bottomGoalGreen : UInt32 = 1
static let topGoalGreen : UInt32 = 2
static let bottomGoalBlue : UInt32 = 4
static let topGoalBlue : UInt32 = 8
static let ball : UInt32 = 16
}
class GamePlayScene: SKScene, SKPhysicsContactDelegate {
var topGoalGreen = SKSpriteNode(imageNamed: "green goal (top).png")
var bottomGoalGreen = SKSpriteNode(imageNamed: "green goal (bottom).png")
var topGoalBlue = SKSpriteNode(imageNamed: "blue goal (top).png")
var bottomGoalBlue = SKSpriteNode(imageNamed: "blue goal (bottom).png")
var ball = SKSpriteNode(imageNamed: "green ball.png")
override func didMoveToView(view: SKView) {
//setup scene
physicsWorld.gravity = CGVector.zeroVector
physicsWorld.gravity = CGVectorMake(0, 0)
physicsWorld.contactDelegate = self
self.scene?.backgroundColor = UIColor.blackColor()
self.scene?.size = CGSize(width: 640, height: 1136)
//Top goal green code
topGoalGreen.position = CGPoint (x: self.size.width * 0.5, y: self.size.width * 1.52)
topGoalGreen.physicsBody = SKPhysicsBody(rectangleOfSize: topGoalGreen.size)
topGoalGreen.size = CGSize (width: 300, height: 309)
topGoalGreen.physicsBody?.dynamic = false
topGoalGreen.physicsBody?.categoryBitMask = PhysicsCatagory.topGoalGreen
topGoalGreen.physicsBody?.collisionBitMask = 0
topGoalGreen.physicsBody?.contactTestBitMask = PhysicsCatagory.ball
self.addChild(topGoalGreen)
//Bottom goal code
bottomGoalGreen.position = CGPoint (x: self.size.width * 0.5, y: self.size.width * 0.252)
bottomGoalGreen.size = CGSize (width: 300, height: 309)
bottomGoalGreen.physicsBody?.dynamic = false
bottomGoalGreen.physicsBody?.categoryBitMask = PhysicsCatagory.bottomGoalGreen
bottomGoalGreen.physicsBody?.contactTestBitMask = PhysicsCatagory.ball
self.addChild(bottomGoalGreen)
//Ball code
ball.position = CGPoint (x: self.size.width * 0.5, y: self.size.width * 0.9)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.size.width / 2)
ball.size = CGSize (width: 80, height: 82)
ball.physicsBody?.dynamic = true
ball.physicsBody?.categoryBitMask = PhysicsCatagory.ball
ball.physicsBody?.collisionBitMask = 0
ball.physicsBody?.contactTestBitMask = PhysicsCatagory.topGoalGreen
ball.physicsBody?.categoryBitMask = PhysicsCatagory.bottomGoalGreen
ball.physicsBody?.collisionBitMask = PhysicsCatagory.bottomGoalGreen
ball.physicsBody?.contactTestBitMask = PhysicsCatagory.bottomGoalGreen
let moveBallUp = SKAction.moveToY(1040, duration: 2)
let moveBallDown = SKAction.moveToY(90, duration: 2)
let moveUpAndDown = SKAction.sequence([moveBallUp, moveBallDown])
let moveUpAndDownForever = SKAction.repeatActionForever(moveUpAndDown)
ball.runAction(moveUpAndDownForever)
self.addChild(ball)
}
func didBeginContact(contact: SKPhysicsContact) {
var firstBody : SKPhysicsBody = contact.bodyA
var secondBody : SKPhysicsBody = contact.bodyB
if (((firstBody.categoryBitMask == PhysicsCatagory.topGoalGreen) && (secondBody.categoryBitMask == PhysicsCatagory.ball)) ||
((firstBody.categoryBitMask == PhysicsCatagory.ball) && (secondBody.categoryBitMask == PhysicsCatagory.topGoalGreen))){
CollisionWithBall(firstBody.node as! SKSpriteNode, ball: secondBody.node as! SKSpriteNode)
NSLog("Collision!")
}
}
func CollisionWithBall(topGoalGreen : SKSpriteNode, ball : SKSpriteNode) {
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
I figured out what I was missing. I was missing a SKPhysicsBody for both goals and ball. Thanks to the other commenters for trying to help me.
//Top goal green code
topGoalGreen.position = CGPoint (x: self.size.width * 0.5, y: self.size.width * 1.67)
topGoalGreen.size = CGSize (width: 400, height: 80)
topGoalGreen.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize (width: 10, height: 10))
topGoalGreen.physicsBody?.dynamic = false
topGoalGreen.physicsBody?.categoryBitMask = PhysicsCatagory.topGoalGreen
topGoalGreen.physicsBody?.contactTestBitMask = PhysicsCatagory.ball
self.addChild(topGoalGreen)
In order to register contact you should set contact delegate.
physicsWorld.contactDelegate = self
Otherwise , you can't use methods like didBeginContact or didEndContact. Also you have to set category, contact and collision bitmasks properly in order to make everything to work. So, next thing would be to set category and contact bit masks properly.
ball.physicsBody?.categoryBitMask = PhysicsCategory.ball
//Contact will be registered when ball makes a contact with top or bottom goal.
ball.physicsBody?.contactTestBitMask = PhysicsCategory.topGoal | PhysicsCategory.bottomGoal
You have to follow this principle as well for top and bottom goal nodes.
Check out this great answer by rickster in order to understand how things works when using physics engine in SpriteKit.