didBeginContact not working in Swift 2 + SpriteKit - swift

I'm working on a game, and I'm using spritekit and Swift.
This is my code:
import SpriteKit
struct collision {
static let arrow:UInt32 = 0x1 << 1
static let runner:UInt32 = 0x1 << 2
static let target:UInt32 = 0x1 << 3
static let targetCenter:UInt32 = 0x1 << 4
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var person = SKSpriteNode()
var box = SKSpriteNode()
var screenSize:CGSize!
var gameScreenSize:CGSize!
var gameStarted:Bool = false
var moveAndRemove = SKAction()
var boxVelocity:NSTimeInterval = 5.5
override func didMoveToView(view: SKView) {
self.physicsWorld.gravity = CGVectorMake(0, -1.0)
self.physicsWorld.contactDelegate = self
screenSize = self.frame.size
gameScreenSize = view.frame.size
createPerson()
}
func createPerson() -> Void {
person.texture = SKTexture(imageNamed:"person")
person.setScale(1.0)
person.size = CGSize(width: 80, height: 80)
person.position = CGPoint(x: screenSize.width / 2, y: 150)
person.physicsBody = SKPhysicsBody(rectangleOfSize: person.size)
person.physicsBody?.affectedByGravity = false
person.physicsBody?.dynamic = false
self.addChild(person)
}
func createTarget() -> Void {
box = SKSpriteNode()
box.size = CGSize(width: 70, height: 100)
box.setScale(1.0)
box.position = CGPoint(x: (screenSize.width / 3) * 2, y: screenSize.height + box.size.height)
box.texture = SKTexture(imageNamed: "box")
box.physicsBody? = SKPhysicsBody(rectangleOfSize: box.size)
box.physicsBody?.categoryBitMask = collision.target
box.physicsBody?.collisionBitMask = collision.arrow
box.physicsBody?.contactTestBitMask = collision.targetCenter
box.physicsBody?.affectedByGravity = false
box.physicsBody?.dynamic = true
box.physicsBody?.usesPreciseCollisionDetection = true
self.addChild(box)
let distance = CGFloat(self.frame.height - box.frame.height)
let moveTargets = SKAction.moveToY(-distance, duration: boxVelocity)
let removeTargets = SKAction.removeFromParent()
moveAndRemove = SKAction.sequence([moveTargets,removeTargets])
box.runAction(moveAndRemove)
}
func createBall() ->Void {
let ball = SKSpriteNode()
ball.size = CGSize(width: 20, height: 22)
ball.zPosition = 5
let moveToXY = CGPoint(x: self.size.width, y: self.size.height)
ball.texture = SKTexture(imageNamed: "ball")
ball.position = CGPointMake(person.position.x + ball.size.width, person.position.y + ball.size.height)
ball.physicsBody? = SKPhysicsBody(rectangleOfSize: ball.size)
ball.physicsBody?.categoryBitMask = collision.arrow
ball.physicsBody?.collisionBitMask = collision.target
ball.physicsBody?.affectedByGravity = false
ball.physicsBody?.dynamic = true
ball.physicsBody?.usesPreciseCollisionDetection = true
let action = SKAction.moveTo(moveToXY, duration: 1.5)
let delay = SKAction.waitForDuration(1.5)
ball.runAction(SKAction.sequence([action,delay]))
self.addChild(ball)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if gameStarted == false {
gameStarted = true
let spawn = SKAction.runBlock { () in
self.createTarget()
}
let delay = SKAction.waitForDuration(1.5)
let spawnDelay = SKAction.sequence([spawn, delay])
let spanDelayForever = SKAction.repeatActionForever(spawnDelay)
self.runAction(spanDelayForever)
} else {
createBall()
boxVelocity -= 0.1
}
}
func didBeginContact(contact: SKPhysicsContact) {
print("Detect")
}
func didEndContact(contact: SKPhysicsContact) {
print("end detect")
}
override func update(currentTime: CFTimeInterval) {
}
}
But when I run the game, the collision between objects does not. I'm trying to solve a while, but found nothing. Can someone help me?
Project files.

Try with these to modifications:
box.physicsBody = SKPhysicsBody(rectangleOfSize: box.size)
box.physicsBody?.categoryBitMask = collision.target
box.physicsBody?.collisionBitMask = collision.arrow
box.physicsBody?.contactTestBitMask = collision.targetCenter
and
ball.physicsBody = SKPhysicsBody(rectangleOfSize: ball.size)
ball.physicsBody?.categoryBitMask = collision.arrow
ball.physicsBody?.collisionBitMask = collision.target
ball.physicsBody?.contactTestBitMask = collision.target
Note the absence of "?" while you init the physicsBody and the new contactTestBitMask

Related

SKSpriteNode will not appear when its physics body is dynamic

The SKSprite will only appear on the scene if .isDynamic = false otherwise it will not show up. Although it does not show up, it seems to be contacting with the other nodes in the scene.
I have tried playing around with the x and y values of the "lemming" node but this still results in it not appearing.
The Question:
What do I need to add or remove in order to make the "lemming" node be affected
by gravity, appear in the scene, and contact correctly with the "cliff" node?
In the GameScene.swift file:
//MARK: - Nodes
var background = SKSpriteNode()
var cliff = SKTexture()
var lemming = SKSpriteNode()
//MARK: -Catergories
let lemmingCatergory : UInt32 = 0x1 << 1
let cliffCatergory : UInt32 = 0x1 << 2
//MARK: - Start of game functions
override func didMove(to view: SKView) {
backgroundColor = UIColor.green
scaleMode = .aspectFit
size = UIScreen.main.bounds.size
physicsWorld.gravity = CGVector(dx: 0, dy: -9.81)
physicsWorld.contactDelegate = self
addBackground()
addCliff()
addLemming()
view.showsPhysics = true
}
//MARK: -Node customization
private func addBackground() {
background = SKSpriteNode(imageNamed: "background")
background.name = "Background"
background.position = CGPoint(x: frame.midX, y: frame.midY)
background.size = UIScreen.main.bounds.size
background.physicsBody = SKPhysicsBody(rectangleOf: background.frame.size)
background.physicsBody?.isDynamic = false
background.physicsBody?.affectedByGravity = false
addChild(background)
}
private func addCliff() {
var cliffNode : SKSpriteNode!
cliff = SKTexture(imageNamed: "cliff")
cliffNode = SKSpriteNode(texture: cliff)
cliffNode.name = "Cliff"
cliffNode.position = CGPoint(x: frame.midX, y: frame.midY)
cliffNode.size = UIScreen.main.bounds.size
cliffNode.physicsBody = SKPhysicsBody(texture: cliff, size: cliff.size())
cliffNode.physicsBody!.categoryBitMask = cliffCatergory
cliffNode.physicsBody!.collisionBitMask = lemmingCatergory
cliffNode.physicsBody!.contactTestBitMask = lemmingCatergory
cliffNode.physicsBody?.isDynamic = true
cliffNode.physicsBody?.affectedByGravity = false
cliffNode.physicsBody?.pinned = true
cliffNode.physicsBody?.allowsRotation = false
addChild(cliffNode)
}
private func addLemming() {
lemming = SKSpriteNode(imageNamed: "lemming")
lemming.size = CGSize(width: lemming.size.width / 15, height: lemming.size.height / 15)
lemming.position = CGPoint(x: 0.5, y: 0)
lemming.physicsBody = SKPhysicsBody(rectangleOf: lemming.frame.size)
lemming.physicsBody!.categoryBitMask = lemmingCatergory
lemming.physicsBody!.collisionBitMask = cliffCatergory
lemming.physicsBody!.contactTestBitMask = cliffCatergory
lemming.physicsBody?.isDynamic = true
lemming.physicsBody?.affectedByGravity = true
addChild(lemming)
}
func didBegin(_ contact: SKPhysicsContact) {
print("Body A: \(String(describing: contact.bodyA.node!.name))")
print("Body B: \(String(describing: contact.bodyB.node!.name))")
}

Swift spritekit didbegincontact being called with delay

This is my GameScene code.
class GameScene: SKScene, SKPhysicsContactDelegate {
let orcWidth = UIScreen.main.bounds.width / 5
var orcCategory:UInt32 = 0x1 << 0
var knightCategory:UInt32 = 0x1 << 1
private var orc = SKSpriteNode()
private var knight = SKSpriteNode()
private var orcWalkingFrames: [SKTexture] = []
private var knightIdleFrames: [SKTexture] = []
private var knightAttackFrame: [SKTexture] = []
var background = SKSpriteNode(imageNamed: "game_background1")
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
setupbackground()
startGame()
}
func setupbackground() {
background.zPosition = 0
background.size = self.frame.size
background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
addChild(background)
}
func startGame() {
buildRandomOrcs()
buildKnight()
}
func stopGame() {
}
func buildOrc(yposition: CGFloat) {
var orcWalkFrames: [SKTexture] = []
let orcAnimatedAtlas = SKTextureAtlas(named: "OrcWalking")
let numImages = orcAnimatedAtlas.textureNames.count
for i in 0...numImages - 1 {
let orcTextureName = "0_Orc_Walking_\(i)"
orcWalkFrames.append(orcAnimatedAtlas.textureNamed(orcTextureName))
}
self.orcWalkingFrames = orcWalkFrames
let firstFrameTexture = orcWalkingFrames[0]
orc = SKSpriteNode(texture: firstFrameTexture)
orc.name = "orc"
orc.position = CGPoint(x: frame.minX-orcWidth/2, y: yposition)
self.orc.zPosition = CGFloat(self.children.count)
orc.scale(to: CGSize(width: orcWidth, height: orcWidth))
orc.physicsBody = SKPhysicsBody(rectangleOf: orc.size, center: orc.position)
orc.physicsBody?.affectedByGravity = false
orc.physicsBody?.isDynamic = true
orc.physicsBody?.categoryBitMask = orcCategory
orc.physicsBody?.contactTestBitMask = knightCategory
orc.physicsBody?.collisionBitMask = knightCategory
addChild(orc)
walkOrc()
moveOrcForward()
}
func buildKnight() {
var knightIdleFrames: [SKTexture] = []
let knightIdleAtlas = SKTextureAtlas(named: "KnightIdle")
let numImages = knightIdleAtlas.textureNames.count
for i in 0...numImages - 1 {
let orcTextureName = "_IDLE_00\(i)"
knightIdleFrames.append(knightIdleAtlas.textureNamed(orcTextureName))
}
self.knightIdleFrames = knightIdleFrames
let firstFrameTexture = knightIdleFrames[0]
knight = SKSpriteNode(texture: firstFrameTexture)
knight.name = "knight"
knight.position = CGPoint(x: frame.maxX-orcWidth/2, y: frame.midY)
self.knight.zPosition = 1
knight.scale(to: CGSize(width: -orcWidth, height: orcWidth))
knight.physicsBody = SKPhysicsBody(rectangleOf: knight.size, center: knight.position)
knight.physicsBody?.affectedByGravity = false
knight.physicsBody?.isDynamic = false
knight.physicsBody?.categoryBitMask = knightCategory
knight.physicsBody?.contactTestBitMask = orcCategory
knight.physicsBody?.collisionBitMask = orcCategory
addChild(knight)
idleKnight()
}
func idleKnight() {
knight.run(SKAction.repeatForever(SKAction.animate(with: knightIdleFrames, timePerFrame: 0.1)))
}
func walkOrc() {
orc.run(SKAction.repeatForever(SKAction.animate(with: orcWalkingFrames,timePerFrame: 0.025)))
}
func moveOrcForward() {
orc.run(SKAction.repeatForever(SKAction.moveBy(x: 55, y: 0, duration: 0.25)))
}
func buildRandomOrcs () {
let wait = SKAction.wait(forDuration: TimeInterval(makeRandomNumberBetween(min: 0, max: 0)))
let spawn = SKAction.run {
self.buildOrc(yposition: self.makeRandomCGFloatNumber())
}
let spawning = SKAction.sequence([spawn,wait])
self.run(SKAction.repeat(spawning, count: 10))
}
func makeRandomCGFloatNumber() -> CGFloat {
let randomNumber = arc4random_uniform(UInt32((frame.maxY-orcWidth/2) - (frame.minY+orcWidth/2))) + UInt32(frame.minY+orcWidth/2)
return CGFloat(randomNumber)
}
func makeRandomNumberBetween (min: Int, max: Int) -> Int{
let randomNumber = arc4random_uniform(UInt32(max - min)) + UInt32(min)
return Int(randomNumber)
}
func didBegin(_ contact: SKPhysicsContact) {
let collision:UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
if collision == orcCategory | knightCategory {
self.scene?.view?.isPaused = true
print("COLLIDED")
}
}
}
The problem is that the scene pauses almost 2-3 seconds after the collision.
I changed the position of knight and delay time changed.
For example, if I set position to frame.minX+orcWidth/2 there is no delay.
What is wrong with my code?
Your problem isn't things are being delayed, your problem is your bounding box is not where you think it is
use view.showPhysics = true to determine where your boxes are
once you realize they are in the wrong spots, go to this line
knight.physicsBody = SKPhysicsBody(rectangleOf: knight.size, center: knight.position)
and fix it
knight.physicsBody = SKPhysicsBody(rectangleOf: knight.size)
Do so for the rest of your bodies
My guess is that manipulations of SKView properties must happen on main thread, i.e.
DispatchQueue.main.async { [unowned self] in
self.scene?.view?.isPaused = true
print("COLLIDED")
}

SpriteKit - didBegin contact is called 30 times instead of 1 time

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.

SKPhysics Contact not functioning properly

I am trying to use the SKPhysicsContactDelegate function in SpriteKit and it will not seem to work. I want one sprite to perform an action when it hits the other. I have set up breakpoints at the didBeginContact function and for some reason my application never calls this function. All help appreciated. Code posted below.
struct PhysicsCatagory {
static let Enemy :UInt32 = 0x1 << 0
static let Slider :UInt32 = 0x1 << 1
static let Circle :UInt32 = 0x1 << 2
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var EnemyTimer = NSTimer()
var Circle = SKSpriteNode()
var Slider = SKSpriteNode()
var FastButton = SKNode()
var Title = SKSpriteNode()
var Text = SKSpriteNode()
var Path = UIBezierPath()
var gameStarted = Bool()
override func didMoveToView(view: SKView) {
self.physicsWorld.contactDelegate = self
self.backgroundColor = UIColor.whiteColor()
Circle = SKSpriteNode(imageNamed:"blueCircle")
Circle.size = CGSize(width: 140, height: 140)
Circle.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
Circle.zPosition = 1.0
self.addChild(Circle)
Slider = SKSpriteNode(imageNamed: "blocker1")
Slider.size = CGSize(width: 15, height: 50)
Slider.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 + 80)
addChild(Slider)
Slider.zPosition = 1.0
moveClockWise()
}
func didBeginContact(contact: SKPhysicsContact) {
if contact.bodyA.node != nil && contact.bodyB.node != nil{
let firstBody = contact.bodyA.node as! SKSpriteNode
let secondBody = contact.bodyB.node as! SKSpriteNode
if ((firstBody.name == "Enemy") && (secondBody.name == "Slider")){
collisionBall(firstBody, Slider: secondBody)
}
else if ((firstBody.name == "Slider") && (secondBody.name == "Enemy")) {
collisionBall(secondBody, Slider: firstBody)
}
}
}
func collisionBall(Enemy : SKSpriteNode, Slider : SKSpriteNode){
Enemy.physicsBody?.dynamic = true
Enemy.physicsBody?.affectedByGravity = true
Enemy.physicsBody?.mass = 4.0
Slider.physicsBody?.mass = 4.0
Enemy.removeAllActions()
Enemy.physicsBody?.contactTestBitMask = 0
Enemy.physicsBody?.collisionBitMask = 0
Enemy.name = nil
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//Slider.hidden = false
FastButton.hidden = false
Title.hidden = true
Text.hidden = true
EnemyTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(GameScene.Enemies), userInfo: nil, repeats: true)
//Physics
Slider.physicsBody?.categoryBitMask = PhysicsCatagory.Slider
Slider.physicsBody?.collisionBitMask = PhysicsCatagory.Enemy
Slider.physicsBody?.contactTestBitMask = PhysicsCatagory.Enemy
Slider.name = "Slider"
Slider.physicsBody?.dynamic = true
Slider.physicsBody?.affectedByGravity = true
if gameStarted == false{
gameStarted = true
}
else if gameStarted == true{
}
}
func moveClockWise(){
let dx = Slider.position.x / 2
let dy = Slider.position.y / 2
let rad = atan2(dy, dx)
let Path = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2, y: self.frame.height / 2), radius: 90, startAngle: rad, endAngle: rad + CGFloat(M_PI * 4), clockwise: true)
let follow = SKAction.followPath(Path.CGPath, asOffset: false, orientToPath: true, speed: 150)
//let rotate = SKAction.rotateByAngle(75, duration: 100)
Slider.runAction(SKAction.repeatActionForever(follow).reversedAction())
//Slider.runAction(SKAction.repeatActionForever(rotate).reversedAction())
}
func Enemies(){
let Enemy = SKSpriteNode(imageNamed: "darkRedDot")
Enemy.size = CGSize(width: 20, height: 20)
//Physics
Enemy.physicsBody = SKPhysicsBody(circleOfRadius: Enemy.size.width / 2)
Enemy.physicsBody?.categoryBitMask = PhysicsCatagory.Enemy
Enemy.physicsBody?.contactTestBitMask = PhysicsCatagory.Slider //| PhysicsCatagory.Circle
Enemy.physicsBody?.collisionBitMask = PhysicsCatagory.Slider //| PhysicsCatagory.Circle
Enemy.physicsBody?.dynamic = true
Enemy.physicsBody?.affectedByGravity = false
Enemy.name = "Enemy"
The contact is not beginning because your slider has no physics body, making it impossible to recognize contact. Unless, it's not in this code, your slider has no physics body, but your enemy does. Try declaring Slider.phisicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "blocker1"), size: Slider.size)
Also, you should read about standard naming conventions in Swift. It is recommended that your variables always start with lowercase letters (eg. enemyTimer, circle, slider, fastButton, etc...).

How to track two different collisions in SpriteKit Swift

I have seen many methods on the internet, but I'm still very confused on how this is done. Ive legitimately have spent 3 hours yesterday on trying to acomplish this, but anyway the question I have is I have 3 main SKSpriteNodes in my game: man, ground, and arrow. Im trying to make it so that when the man jumps he is only able to jump once until returning back to the ground. My plan is to have it so that when the jump button is pressed a condition is changed and won't be changed back till the man hits the ground again. Im also trying to make it so that when an arrow contacts him it will be a game over and run a line of code. This is the code I have so far
//
// GameScene.swift
// arrow jump
//
// Created by Joy Cafiero on 3/29/16.
// Copyright (c) 2016 3rd Dimension Studios inc. All rights reserved.
//
import SpriteKit
var timer = NSTimer()
var condition = 1
var arrow = SKSpriteNode()
var man = SKSpriteNode()
var bg = SKSpriteNode()
var ground = SKSpriteNode()
var buttonRight = SKSpriteNode()
var buttonLeft = SKSpriteNode()
var buttonJump = SKSpriteNode()
let moveGrounRight = SKAction.moveByX(200, y: 0, duration: 1)
let repeatMoveGroundRight = SKAction.repeatActionForever(moveGrounRight)
let moveGrounLeft = SKAction.moveByX(-200, y: 0, duration: 1)
let repeatMoveGroundLeft = SKAction.repeatActionForever(moveGrounLeft)
let runningMan1 = (SKTexture (imageNamed: "running man1.png"))
let runningMan2 = (SKTexture (imageNamed: "running man2.png"))
let runningMan3 = (SKTexture (imageNamed: "running man3.png"))
let runningMan4 = (SKTexture (imageNamed: "running man4.png"))
let runningMan5 = (SKTexture (imageNamed: "running man5.png"))
let runningMan6 = (SKTexture (imageNamed: "running man6.png"))
let nuetralMan = (SKTexture (imageNamed: "running man nuetral.png"))
let jumpingMan1 = (SKTexture (imageNamed: "jumping man1"))
let jumpingMan2 = (SKTexture (imageNamed: "jumping man2"))
let jumpingMan3 = (SKTexture (imageNamed: "jumping man3"))
let animation = SKAction.animateWithTextures([ runningMan1, runningMan2, runningMan3, runningMan4, runningMan5, runningMan6], timePerFrame: 0.15)
let jumpingAnimation = SKAction.animateWithTextures([jumpingMan1, jumpingMan2, jumpingMan3], timePerFrame: 0.1)
let nuetralAnimation = SKAction.animateWithTextures([nuetralMan], timePerFrame: 0.05)
let repeatAnimation = SKAction.repeatActionForever(animation)
let manGroup:UInt32 = 1
let groundGroup:UInt32 = 2
let arrowGroup:UInt32 = 0x1 << 3
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.physicsWorld.contactDelegate = self
self.physicsWorld.gravity = CGVectorMake(0, -5)
man = SKSpriteNode(texture: nuetralMan)
man.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
man.size = CGSize(width: man.size.width * 2, height: man.size.height * 2)
man.zPosition = 15
man.physicsBody = SKPhysicsBody(rectangleOfSize: man.size)
man.physicsBody?.dynamic = true
man.physicsBody?.allowsRotation = false
man.physicsBody?.categoryBitMask = manGroup
man.physicsBody?.contactTestBitMask = groundGroup
self.addChild(man)
let bgTexture = (SKTexture(imageNamed: "wild west landscape.png"))
bg = SKSpriteNode(texture: bgTexture)
bg.size = CGSize(width: self.frame.width, height: self.frame.height)
bg.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) + 100)
bg.zPosition = -1
self.addChild(bg)
let groundtexture = (SKTexture(imageNamed: "sandy ground.png"))
ground = SKSpriteNode(texture: groundtexture)
ground.size = CGSize(width: CGRectGetMaxX(self.frame), height: ground.size.height)
ground.position = CGPointMake(CGRectGetMidX(self.frame), 0)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.width, ground.size.height-255))
ground.physicsBody?.dynamic = false
ground.zPosition = 20
ground.physicsBody?.categoryBitMask = groundGroup
ground.physicsBody?.contactTestBitMask = manGroup
self.addChild(ground)
timer = NSTimer.scheduledTimerWithTimeInterval(7, target: self, selector: Selector("timerUpdate"), userInfo: nil, repeats: true)
buttonRight.color = SKColor.redColor()
buttonRight.position = CGPointMake(200, 200)
buttonRight.size = CGSize(width: 100, height: 100)
buttonRight.zPosition = 25
self.addChild(buttonRight)
buttonLeft.color = SKColor.redColor()
buttonLeft.position = CGPointMake(100, 200)
buttonLeft.size = CGSize(width: 100, height: 100)
buttonLeft.zPosition = 25
self.addChild(buttonLeft)
buttonJump.color = SKColor.greenColor()
buttonJump.position = CGPointMake(CGRectGetMaxX(self.frame) - 200, 200)
buttonJump.size = CGSize(width: 100, height: 100)
buttonJump.zPosition = 25
self.addChild(buttonJump)
}
func timerUpdate() {
let random = Int(arc4random_uniform(3))
var timeIncrease:NSTimeInterval = 0
var randomArrow = [self.frame.height / 20 + CGRectGetMidY(self.frame) - 65, self.frame.height / 20 + self.frame.height / 20 + CGRectGetMidY(self.frame) - 65, self.frame.height / 20 + self.frame.height / 20 + self.frame.height / 20 + CGRectGetMidY(self.frame) - 65, self.frame.height / 20 + self.frame.height / 20 + self.frame.height / 20 + CGRectGetMidY(self.frame) - 65]
timeIncrease = timeIncrease + 7
let arrowTexture = (SKTexture(imageNamed: "arrow.png"))
let movingArrow = SKAction.moveByX(-self.frame.size.width, y: 0, duration: NSTimeInterval(self.frame.size.width/100)-5+timeIncrease)
let removeArrows = SKAction.removeFromParent()
let repeatmoveArrows = SKAction.sequence([movingArrow, removeArrows])
arrow = SKSpriteNode(texture: arrowTexture)
arrow.size = CGSize(width: arrow.size.width, height: arrow.size.height)
arrow.position = CGPointMake(CGRectGetMaxX(self.frame), randomArrow[random])
arrow.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(arrowTexture.size().width - 100, arrow.size.height / 2))
arrow.physicsBody?.dynamic = false
arrow.zPosition = 10
arrow.physicsBody?.categoryBitMask = arrowGroup
arrow.physicsBody?.contactTestBitMask = manGroup
arrow.runAction(repeatmoveArrows)
arrow.physicsBody?.categoryBitMask = arrowGroup
arrow.physicsBody?.contactTestBitMask = manGroup
self.addChild(arrow)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if buttonRight.containsPoint(location) {
man.xScale = 1
man.runAction(repeatMoveGroundRight, withKey: "MoveRight")
man.runAction(repeatAnimation, withKey: "Run")
}
if buttonLeft.containsPoint(location) {
man.xScale = -1
man.runAction(repeatMoveGroundLeft, withKey: "MoveLeft")
man.runAction(repeatAnimation, withKey: "Run")
}
if buttonJump.containsPoint(location) {
if(condition == 1) {
man.physicsBody?.velocity = CGVectorMake(0, 0)
man.physicsBody?.applyImpulse(CGVectorMake(0, 400))
man.runAction(jumpingAnimation)
}
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if buttonRight.containsPoint(location) {
man.removeActionForKey("MoveRight")
man.removeActionForKey("Run")
man.texture = nuetralMan
}
if buttonLeft.containsPoint(location) {
man.removeActionForKey("MoveLeft")
man.removeActionForKey("Run")
man.texture = nuetralMan
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if buttonRight.containsPoint(location) {
man.removeActionForKey("MoveRight")
man.removeActionForKey("Run")
man.texture = nuetralMan
}
if buttonLeft.containsPoint(location) {
man.removeActionForKey("MoveLeft")
man.removeActionForKey("Run")
man.texture = nuetralMan
}
}
func didBeginContact(contact: SKPhysicsContact) {
condition = 1
man.texture = nuetralMan
print("contact")
}
func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
}