MY didBeginContact() FUNCTION DOES NOT WORK SWIFT SPRITE KIT [closed] - swift

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi I have been trying to solve this problem for a long time, my problem is that my didBeginContact() does not work the "rocket" collides with the "missiles" and they get pushed down but it does not run the function, what can I do to fix it?
Thanks in advance.
//
// PlaysScene.swift
// Pocket Rocket3
//
// Created by Lucas Farleigh on 27/11/2014.
// Copyright (c) 2014 Lucas Farleigh. All rights reserved.
//
import spriteKit
class PlayScene:SKScene, SKPhysicsContactDelegate{
//declaring the node in this scene!
let background = SKSpriteNode(imageNamed: "background")
let bara = SKSpriteNode(imageNamed: "bar6")
let barb = SKSpriteNode(imageNamed: "bar6")
let barc = SKSpriteNode(imageNamed: "bar6")
let bard = SKSpriteNode(imageNamed: "bar6")
let bare = SKSpriteNode(imageNamed: "bar6")
let barf = SKSpriteNode(imageNamed: "bar6")
let barg = SKSpriteNode(imageNamed: "bar6")
let barh = SKSpriteNode(imageNamed: "bar6")
let bari = SKSpriteNode(imageNamed: "bar6")
let barj = SKSpriteNode(imageNamed: "bar6")
let bar1 = SKSpriteNode(imageNamed: "bar6")
let bar2 = SKSpriteNode(imageNamed: "bar6")
let bar3 = SKSpriteNode(imageNamed: "bar6")
let bar4 = SKSpriteNode(imageNamed: "bar6")
let bar5 = SKSpriteNode(imageNamed: "bar6")
let bar6 = SKSpriteNode(imageNamed: "bar6")
let bar7 = SKSpriteNode(imageNamed: "bar6")
let bar8 = SKSpriteNode(imageNamed: "bar6")
let bar9 = SKSpriteNode(imageNamed: "bar6")
let bar10 = SKSpriteNode(imageNamed: "bar6")
let missile1 = SKSpriteNode(imageNamed:"Missile")
let missile2 = SKSpriteNode(imageNamed:"Missile")
let missile3 = SKSpriteNode(imageNamed:"Missile")
let missile4 = SKSpriteNode(imageNamed:"Missile")
let missile5 = SKSpriteNode(imageNamed:"Missile")
let missile6 = SKSpriteNode(imageNamed:"Missile")
let missile7 = SKSpriteNode(imageNamed:"Missile")
let missile8 = SKSpriteNode(imageNamed:"Missile")
let missile9 = SKSpriteNode(imageNamed:"Missile")
let missile10 = SKSpriteNode(imageNamed:"Missile")
let missile11 = SKSpriteNode(imageNamed:"Missile")
let missile12 = SKSpriteNode(imageNamed:"Missile")
let missile13 = SKSpriteNode(imageNamed:"Missile")
let missile14 = SKSpriteNode(imageNamed:"Missile")
let missile15 = SKSpriteNode(imageNamed:"Missile")
let rocket = SKSpriteNode(imageNamed:"rocket")
var leftTouch = false
var rightTouch = false
enum colideType:UInt32{
case rocket = 1
case missile = 2
}
var actionmove = SKAction.moveToY(-150, duration: 15)
override func didMoveToView(view: SKView) {
self.physicsWorld.contactDelegate = self
let print = SKAction.runBlock({
println("moved")
})
let actionmove1 = SKAction.sequence([actionmove,print])
var delay = SKAction.waitForDuration(NSTimeInterval(1.5))
var delchild = SKAction.removeFromParent()
var rand = arc4random_uniform(10)
self.rocket.physicsBody = SKPhysicsBody(rectangleOfSize: self.rocket.size)
self.physicsBody?.categoryBitMask = colideType.rocket.toRaw()
self.physicsBody?.contactTestBitMask = colideType.missile.toRaw()
rocket.physicsBody?.affectedByGravity = false
rocket.physicsBody?.contactTestBitMask = colideType.missile.toRaw()
rocket.physicsBody?.collisionBitMask = colideType.missile.toRaw()
missile1.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile1.size)
missile2.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile2.size)
missile3.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile3.size)
missile4.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile4.size)
missile5.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile5.size)
missile6.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile6.size)
missile7.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile7.size)
missile8.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile8.size)
missile9.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile9.size)
missile10.physicsBody = SKPhysicsBody(rectangleOfSize: self.missile10.size)
missile1.physicsBody?.dynamic = false
missile2.physicsBody?.dynamic = false
missile3.physicsBody?.dynamic = false
missile4.physicsBody?.dynamic = false
missile5.physicsBody?.dynamic = false
missile6.physicsBody?.dynamic = false
missile7.physicsBody?.dynamic = false
missile8.physicsBody?.dynamic = false
missile9.physicsBody?.dynamic = false
missile10.physicsBody?.dynamic = false
missile1.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile2.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile3.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile4.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile5.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile6.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile7.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile8.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile9.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile10.physicsBody?.categoryBitMask = colideType.missile.toRaw()
missile1.physicsBody?.affectedByGravity = false
missile2.physicsBody?.affectedByGravity = false
missile3.physicsBody?.affectedByGravity = false
missile4.physicsBody?.affectedByGravity = false
missile5.physicsBody?.affectedByGravity = false
missile6.physicsBody?.affectedByGravity = false
missile7.physicsBody?.affectedByGravity = false
missile8.physicsBody?.affectedByGravity = false
missile9.physicsBody?.affectedByGravity = false
missile10.physicsBody?.affectedByGravity = false
missile1.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile2.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile3.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile4.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile5.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile6.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile7.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile8.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile9.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile10.physicsBody?.contactTestBitMask = colideType.rocket.toRaw()
missile1.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile2.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile3.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile4.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile5.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile6.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile7.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile8.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile9.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile10.physicsBody?.collisionBitMask = colideType.rocket.toRaw()
missile1.yScale = 0.35
missile2.yScale = 0.35
missile3.yScale = 0.35
missile4.yScale = 0.35
missile5.yScale = 0.35
missile6.yScale = 0.35
missile7.yScale = 0.35
missile8.yScale = 0.35
missile9.yScale = 0.35
missile10.yScale = 0.35
missile1.xScale = 0.6
missile2.xScale = 0.6
missile3.xScale = 0.6
missile4.xScale = 0.6
missile5.xScale = 0.6
missile6.xScale = 0.6
missile7.xScale = 0.6
missile8.xScale = 0.6
missile9.xScale = 0.6
missile10.xScale = 0.6
let delayA = SKAction.waitForDuration(NSTimeInterval(2.0))
let delayB = SKAction.waitForDuration(NSTimeInterval(4.0))
let delayC = SKAction.waitForDuration(NSTimeInterval(6.0))
let delayD = SKAction.waitForDuration(NSTimeInterval(8.0))
let delayE = SKAction.waitForDuration(NSTimeInterval(10.0))
let delayF = SKAction.waitForDuration(NSTimeInterval(12.0))
let delayG = SKAction.waitForDuration(NSTimeInterval(14.0))
let delayH = SKAction.waitForDuration(NSTimeInterval(16.0))
let delayI = SKAction.waitForDuration(NSTimeInterval(18.0))
let delayJ = SKAction.waitForDuration(NSTimeInterval(20.0))
var missile1Hide = SKAction.runBlock({
self.missile1.hidden = true
})
var missile2Hide = SKAction.runBlock({
self.missile2.hidden = true
})
var missile3Hide = SKAction.runBlock({
self.missile3.hidden = true
})
var missile4Hide = SKAction.runBlock({
self.missile4.hidden = true
})
var missile5Hide = SKAction.runBlock({
self.missile5.hidden = true
})
var missile6Hide = SKAction.runBlock({
self.missile6.hidden = true
})
var missile7Hide = SKAction.runBlock({
self.missile7.hidden = true
})
var missile8Hide = SKAction.runBlock({
self.missile8.hidden = true
})
var missile9Hide = SKAction.runBlock({
self.missile9.hidden = true
})
var missile10Hide = SKAction.runBlock({
self.missile10.hidden = true
})
var missile1show = SKAction.runBlock({
self.missile1.hidden = false
})
var missile2show = SKAction.runBlock({
self.missile2.hidden = false
})
var missile3show = SKAction.runBlock({
self.missile3.hidden = false
})
var missile4show = SKAction.runBlock({
self.missile4.hidden = false
})
var missile5show = SKAction.runBlock({
self.missile5.hidden = false
})
var missile6show = SKAction.runBlock({
self.missile6.hidden = false
})
var missile7show = SKAction.runBlock({
self.missile7.hidden = false
})
var missile8show = SKAction.runBlock({
self.missile8.hidden = false
})
var missile9show = SKAction.runBlock({
self.missile9.hidden = false
})
var missile10show = SKAction.runBlock({
self.missile10.hidden = false
})
var position1 = SKAction.runBlock({
println("1")
self.missile1.position = CGPointMake(600,850)
})
var position2 = SKAction.runBlock({
println("2")
self.missile2.position = CGPointMake(300,850)
})
var position3 = SKAction.runBlock({
self.missile3.position = CGPointMake(100,850)
println("3")
})
var position4 = SKAction.runBlock({
println("4")
self.missile4.position = CGPointMake(900,850)
})
var position5 = SKAction.runBlock({
println("5")
self.missile5.position = CGPointMake(300,850)
})
var position6 = SKAction.runBlock({
println("6")
self.missile6.position = CGPointMake(600,850)
})
var position7 = SKAction.runBlock({
println("7")
self.missile7.position = CGPointMake(200,850)
})
var position8 = SKAction.runBlock({
println("8")
self.missile8.position = CGPointMake(600,850)
})
var position9 = SKAction.runBlock({
println("9")
self.missile9.position = CGPointMake(900,850)
})
var position10 = SKAction.runBlock({
println("10")
self.missile10.position = CGPointMake(200,850)
})
let sequence1 = SKAction.sequence([missile1Hide,delayA,position1,missile1show,actionmove])
let sequence2 = SKAction.sequence([missile2Hide,delayB,position2,missile2show,actionmove])
let sequence3 = SKAction.sequence([missile3Hide,delayC,position3,missile3show,actionmove])
let sequence4 = SKAction.sequence([missile4Hide,delayD,position4,missile4show,actionmove])
let sequence5 = SKAction.sequence([missile5Hide,delayE,position5,missile5show,actionmove])
let sequence6 = SKAction.sequence([missile6Hide,delayF,position6,missile6show,actionmove])
let sequence7 = SKAction.sequence([missile7Hide,delayG,position7,missile7show,actionmove])
let sequence8 = SKAction.sequence([missile8Hide,delayH,position8,missile8show,actionmove])
let sequence9 = SKAction.sequence([missile9Hide,delayI,position9,missile9show,actionmove])
let sequence10 = SKAction.sequence([missile10Hide,delayJ,position10,missile10show,actionmove])
let s1 = SKAction.sequence([delayA,position1,actionmove1])
let s2 = SKAction.sequence([delayB,position2,actionmove1])
let s3 = SKAction.sequence([delayC,position3,actionmove1])
let s4 = SKAction.sequence([delayD,position4,actionmove1])
let s5 = SKAction.sequence([delayE,position5,actionmove1])
let s6 = SKAction.sequence([delayF,position6,actionmove1])
let s7 = SKAction.sequence([delayG,position7,actionmove1])
let s8 = SKAction.sequence([delayH,position8,actionmove1])
let s9 = SKAction.sequence([delayI,position9,actionmove1])
let s10 = SKAction.sequence([delayJ,position10,actionmove1])
let r1 = SKAction.repeatActionForever(s1)
let r2 = SKAction.repeatActionForever(s2)
let r3 = SKAction.repeatActionForever(s3)
let r4 = SKAction.repeatActionForever(s4)
let r5 = SKAction.repeatActionForever(s5)
let r6 = SKAction.repeatActionForever(s6)
let r7 = SKAction.repeatActionForever(s7)
let r8 = SKAction.repeatActionForever(s8)
let r9 = SKAction.repeatActionForever(s9)
let r10 = SKAction.repeatActionForever(s10)
//actionmove: making it smooth
//doing stuff with the background
background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
background.yScale = 10.0
background.xScale = 10.0
addChild(background)
addChild(rocket)
rocket.yScale = 0.3
rocket.xScale = 0.6
addChild(missile1)
addChild(missile2)
addChild(missile3)
addChild(missile4)
addChild(missile5)
addChild(missile6)
addChild(missile7)
addChild(missile8)
addChild(missile9)
addChild(missile10)
self.missile1.runAction(r1, completion:{
self.missile1.runAction(r1)
})
self.missile2.runAction(r2, completion:{
self.missile1.runAction(r2)
})
self.missile3.runAction(r3, completion:{
self.missile1.runAction(r3)
})
self.missile4.runAction(r4, completion:{
self.missile1.runAction(r4)
})
self.missile5.runAction(r5, completion:{
self.missile1.runAction(r5)
})
self.missile6.runAction(r6, completion:{
self.missile1.runAction(r6) })
self.missile7.runAction(r7, completion:{
self.missile1.runAction(r7)
})
self.missile8.runAction(r8, completion:{
self.missile1.runAction(r8)
})
self.missile9.runAction(r9, completion:{
self.missile1.runAction(r9)
})
self.missile10.runAction(r10, completion:{
self.missile1.runAction(r10)
})
rocket.position = CGPointMake(CGRectGetMidX(self.frame), 200)
func didBeginContact(contact: SKPhysicsContact){
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene{
let skView = self.view as SKView!
skView.presentScene(scene)
}
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch in touches {
let location = touch.locationInNode(self)
var node = self.nodeAtPoint(location)
var loc = location.x
var tapLoc = SKAction.moveToX(loc, duration: 3.5)
tapLoc.timingMode = SKActionTimingMode.EaseOut
rocket.runAction(tapLoc)
}
}
}

I believe you are missing in didMoveToView:
//not sure if it is needed but almost everyone sets the gravity to 0,0 unless needed
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
Also didBeginContact should be outside of didMoveToView and you have it inside.
Hopefully that helps.

Related

SpriteKit - Collision Off after HIT

I am writing a spritekit game and I have a problem, I would like the framework not to detect collisions after it is detected. For example, the player is dealt damage and becomes insensitive to attacks, e.g. for 20 seconds. Now when a collision is detected, it is detected all the time (e.g. 50 times)
Is there a way to temporarily disable collisions ??
Player code :
func createPlayer() {
var walkFrames: [SKTexture] = []
var walkFrames2: [SKTexture] = []
var walkFrames3: [SKTexture] = []
var walkFrames4: [SKTexture] = []
// let spaceShipTexture = SKTexture(imageNamed: "p2.png")
let playerAnimatedAtlas = SKTextureAtlas(named: "walk")
let playerAnimatedAtlas_idle = SKTextureAtlas(named: "idle")
let playerAnimatedAtlas_jump = SKTextureAtlas(named: "jump")
let playerAnimatedAtlas_attack = SKTextureAtlas(named: "attack")
var _: [SKTexture] = []
for i in 0...6 {
let playerTextureName = "1_entity_000_WALK_00\(i).png"
walkFrames.append(playerAnimatedAtlas.textureNamed(playerTextureName))
}
for z in 0...6 {
let playerTextureName_idle = "1_entity_000_IDLE_00\(z).png"
walkFrames2.append(playerAnimatedAtlas_idle.textureNamed(playerTextureName_idle))
}
for p in 0...6 {
let playerTextureName_jump = "1_entity_000_JUMP_00\(p).png"
walkFrames3.append(playerAnimatedAtlas_jump.textureNamed(playerTextureName_jump))
}
for k in 0...6 {
let playerTextureName_attack = "1_entity_000_ATTACK_00\(k).png"
walkFrames4.append(playerAnimatedAtlas_attack.textureNamed(playerTextureName_attack))
}
playerWalkingFrames = walkFrames
let firstFrameTexture = playerWalkingFrames[0]
player.position = CGPoint(x: -1050, y: -90 )
//player.setScale(0.090)
player.size = CGSize(width: 170, height: 120)
// player.physicsBody = SKPhysicsBody(rectangleOf:CGSize(width: 35, height: 100))
let spaceShipTexture = SKTexture(imageNamed: "p2.png")
let texturedSpaceShip = SKSpriteNode(texture: spaceShipTexture)
player.physicsBody = SKPhysicsBody(texture: spaceShipTexture , size: CGSize(width: player.size.width,
height: player.size.height));
player.physicsBody?.usesPreciseCollisionDetection = true
//player.physicsBody = SKPhysicsBody(texture: play, size: player.size)
player.physicsBody?.allowsRotation = false
player.physicsBody?.categoryBitMask = playerCategory
player.physicsBody?.collisionBitMask = enemy1Category
//player.physicsBody?.contactTestBitMask = enemy1Category
playerWalkingFrames_idle = walkFrames2
playerWalkingFrames_jump = walkFrames3
playerWalkingFrames_attack = walkFrames4
self.addChild(player)
}
collision code :
func didBegin(_ contact: SKPhysicsContact) {
let collison: UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
if collison == playerCategory | enemy1Category{
print("COLLISION") }
else {
//print("Brak Kolizji" )
}
if collison == playermieczCategory | enemy1Category {
print("miecz")
}
if collison == playermieczCategory | piratkaCategory {
print("miecz_Piratka")
// health -= 0.2
// piratka.isHidden = true
}
if collison == playerCategory | piratkaCategory{
// if collison == nil {return}
player.physicsBody?.contactTestBitMask = 0
// czarny.physicsBody?.applyImpulse(CGVector(dx: 10, dy: 0))
// DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) {
// self.playerhealth -= 0.01
// print("nico")
print("HIT3")
// }
}

What can I do about `MTLTextureDescriptor has invalid pixelFormat (0)?

Upon initialization of my scene, on rare occasions the app will crash with this error
com.apple.scenekit.scnview-renderer (18): signal SIGABRT
The following is printed in the console
-[MTLTextureDescriptorInternal validateWithDevice:]:1097: failed assertion `MTLTextureDescriptor has invalid pixelFormat (0).'
Lastly, here is the function which is called before the crash
func setupRandomScene() {
self.scene.rootNode.childNodes.forEach({ (node) in
node.removeFromParentNode()
})
DispatchQueue.main.async {
if !Model.shared.hasSeenTooltips {
self.scene = SCNScene(named: "art.scnassets/levels/level\(0).scn")!
} else {
switch Model.shared.level {
case 1...10:
let randomInt = Int.random(in: 1...8)
self.scene = SCNScene(named: "art.scnassets/levels/level\(randomInt).scn")!
case 11...20:
let randomInt = Int.random(in: 1...16)
self.scene = SCNScene(named: "art.scnassets/levels/level\(randomInt).scn")!
default:
let randomInt = Int.random(in: 9...40)
self.scene = SCNScene(named: "art.scnassets/levels/level\(randomInt).scn")!
}
}
let randomColorInt = Int.random(in: 1...4)
switch randomColorInt {
case 1:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/purple")
case 2:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/pink")
case 3:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/orange")
case 4:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/teal")
case 5:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/cyan")
default:
self.scene.background.contents = UIImage(named: "art.scnassets/bg/blue")
}
self.scene.rootNode.childNode(withName: "road", recursively: true)?.geometry?.materials.first?.diffuse.contents = UIColor.black
self.scene.rootNode.childNode(withName: "finishPlatform", recursively: true)?.geometry?.materials.first?.diffuse.contents = UIColor.black
self.scene.rootNode.addChildNode(self.cameraNode)
self.scene.physicsWorld.contactDelegate = self
self.scene.physicsWorld.gravity = SCNVector3(0, -9.8, 0)
self.playerNode = SCNNode()
self.setupPlayerNode()
self.setupSounds()
self.dancingAnimation = SCNAnimation(named: "art.scnassets/stickman/dance\(Int.random(in: 1...10)).scnanim")
let directionalLight = SCNNode()
directionalLight.name = "directional"
directionalLight.position = SCNVector3(-10, 50, -100)
directionalLight.light = SCNLight()
directionalLight.light?.type = .directional
directionalLight.light?.castsShadow = true
directionalLight.light?.shadowRadius = 2 // 1000
directionalLight.light?.shadowSampleCount = 20 // 20
directionalLight.light?.shadowMapSize = CGSize(width: 2000, height: 2000)
directionalLight.light?.intensity = 2000
directionalLight.eulerAngles = SCNVector3(0, -toRadians(angle: 150), -toRadians(angle: 60))
self.scene.rootNode.addChildNode(directionalLight)
let ambientLight = SCNNode()
ambientLight.name = "ambient"
ambientLight.light = SCNLight()
ambientLight.light?.castsShadow = false
ambientLight.light?.type = .ambient
ambientLight.light?.color = UIColor.darkGray
ambientLight.light?.intensity = 5000
self.scene.rootNode.addChildNode(ambientLight)
self.cameraNode.position = SCNVector3(self.playerNode.position.x, self.playerNode.position.y + 5, self.playerNode.position.z - 9)
self.cameraNode.eulerAngles = SCNVector3(-toRadians(angle: 5), -toRadians(angle: 180), 0)
self.cameraNode.camera = SCNCamera()
self.gameState = .menu
self.scnView = nil
self.scnView = self.view as? SCNView
if let _ = self.scnView {
self.scnView!.delegate = self
self.overlayScene = OverlayScene(with: self.overlaySceneSize, isLive: self.broadcastController.isBroadcasting)
self.scnView!.overlaySKScene = self.overlayScene
self.scnView!.present(self.scene, with: .fade(with: .white, duration: 1), incomingPointOfView: nil, completionHandler: nil)
}
if !Model.shared.soundIsMuted {
self.playerNode.runAction(self.playWooshSound)
}
self.positiveHaptic.prepare()
}
}

skphysicsbody to skspritenode error

Here is the code:
import SpriteKit
import CoreMotion
struct PhysicsCatagory {
static let Player :UInt32 = 0x1 << 0
static let shark :UInt32 = 0x1 << 1
static let jellyfish :UInt32 = 0x1 << 2
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var Player = SKSpriteNode()
var game = true
var playerPos = false
var ScoreCount = 0
let myLabel = SKLabelNode(fontNamed: "3D-Thirteen-Pixel-Fonts")
var HighScore = 0
let DisplayScore = SKLabelNode(fontNamed: "3D-Thirteen-Pixel-Fonts")
let LeaderBoardScore = SKLabelNode(fontNamed: "3D-Thirteen-Pixel-Fonts")
let LeaderBoardHighscore = SKLabelNode(fontNamed: "3D-Thirteen-Pixel-Fonts")
var CheckGameState = false
let playButton = SKSpriteNode(imageNamed: "Play")
let Scores = SKSpriteNode(imageNamed: "LeaderBoard")
var PlayerUpState = false
var PlayerDownState = false
var ifPlayerDrawJustCalled = false
var TextureAtlas = SKTextureAtlas()
var TextureArray = [SKTexture]()
var TextureAtlas2 = SKTextureAtlas()
var TextureArray2 = [SKTexture]()
var TextureAtlas3 = SKTextureAtlas()
var TextureArray3 = [SKTexture]()
var motionManager: CMMotionManager!
var fishYpos = 115.0
let shark = SKSpriteNode(imageNamed: "shark")
let jellyfish = SKSpriteNode(imageNamed: "jellyfish")
override func didMoveToView(view: SKView) {
print("called")
motionManager = CMMotionManager()
motionManager.startGyroUpdates()
motionManager.gyroUpdateInterval = 0.02
backgroundColor = UIColor(red: 0.0, green: 7.0, blue: 1.0, alpha: 1.0)
let HighscoreDefault = NSUserDefaults.standardUserDefaults()
if(HighscoreDefault.valueForKey("Highscore") != nil){
HighScore = HighscoreDefault.valueForKey("Highscore") as! Int
}
TextureAtlas = SKTextureAtlas(named: "Images")
TextureArray.append(SKTexture(imageNamed: "win_1.png"))
TextureArray.append(SKTexture(imageNamed: "win_2.png"))
TextureArray.append(SKTexture(imageNamed: "win_3.png"))
TextureArray.append(SKTexture(imageNamed: "win_4.png"))
TextureAtlas3 = SKTextureAtlas(named: "Images")
TextureArray3.append(SKTexture(imageNamed: "jellyfish_1.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_2.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_3.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_4.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_5.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_6.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_7.png"))
TextureArray3.append(SKTexture(imageNamed: "jellyfish_8.png"))
TextureAtlas2 = SKTextureAtlas(named: "Images")
TextureArray2.append(SKTexture(imageNamed: "shark_1.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_2.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_3.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_4.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_5.png"))
TextureArray2.append(SKTexture(imageNamed: "shark_6.png"))
Player = SKSpriteNode(imageNamed: TextureAtlas.textureNames[0])
self.physicsWorld.contactDelegate = self
Player.zPosition = 10.0
Player.position = CGPoint(x: 80, y: fishYpos)
Player.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 30, height: 30))
Player.physicsBody?.dynamic = false
Player.physicsBody?.affectedByGravity = false
myLabel.text = "\(ScoreCount)"
myLabel.fontSize = 70
myLabel.position = CGPointMake(CGRectGetMidX(self.frame), frame.size.height-150)
myLabel.zPosition = 18.0
addChild(myLabel)
addChild(Player)
Player.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(TextureArray, timePerFrame: 0.20)))
var BubbleTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self,selector: "addBubble", userInfo: nil, repeats: true)
var Gyro = NSTimer.scheduledTimerWithTimeInterval(0.02, target:self,selector: "gyroFunction", userInfo: nil, repeats: true)
var MainTimer1 = NSTimer.scheduledTimerWithTimeInterval(1, target:self,selector: "RunTimeTimer", userInfo: nil, repeats: true)
var sharkTimer = NSTimer.scheduledTimerWithTimeInterval(0.70, target: self, selector: "RunSharkTimer", userInfo: nil, repeats: true)
var jellyfishTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "RunJellyfishTimer", userInfo: nil, repeats: true)
}
func addBubble(){
let randomNum1 = Int(arc4random_uniform(3))
if(randomNum1 == 2){
let randomNum2 = Int(arc4random_uniform(2))
if(randomNum2 == 1){
let Bubble1 = SKSpriteNode(imageNamed: "Bubble1")
Bubble1.position.x = Player.position.x+9
Bubble1.position.y = Player.position.y
Bubble1.zPosition = 2.0
addChild(Bubble1)
Bubble1.runAction(SKAction.moveToY( frame.size.height+20, duration: 3.0))
}
if(randomNum2 == 0){
let Bubble2 = SKSpriteNode(imageNamed: "Bubble2")
Bubble2.position.x = Player.position.x+9
Bubble2.position.y = Player.position.y
Bubble2.zPosition = 3.0
addChild(Bubble2)
Bubble2.runAction(SKAction.moveToY( frame.size.height+20, duration: 3.0))
}
}
}
func RunTimeTimer(){
if(game == true){
timer()
}
}
func RunSharkTimer(){
if(game == true){
addShark()
}
}
func RunJellyfishTimer(){
if(game == true){
addJellyfish()
}
}
func gyroFunction(){
if let gyro_y = motionManager.gyroData?.rotationRate.y {
if(fishYpos+gyro_y*(-10) > 115){
if(CGFloat(fishYpos+gyro_y*(-10)) < frame.size.height-115){
fishYpos = fishYpos+gyro_y*(-10)
let fishAction = SKAction.moveToY(CGFloat(fishYpos), duration: 0.05)
Player.runAction(fishAction)
}
}
}
}
func didBeginContact(contact: SKPhysicsContact) {
let firstBody = contact.bodyA as! SKSpriteNode
let secondBody = contact.bodyB as! SKSpriteNode
if(((firstBody.name == "Player") && (secondBody.name == "shark")) || (firstBody.name == "shark") && (secondBody.name == "Player") || ((firstBody.name == "Player") && (secondBody.name == "jellyfish")) || (firstBody.name == "jellyfish") && (secondBody.name == "Player")){
game = false
if(CheckGameState == false){
playButton.xScale = 1.9
playButton.yScale = 1.9
playButton.zPosition = 12.0
playButton.position = CGPoint(x: frame.midX-50, y: frame.midY-140)
playButton.name = "playButton"
playButton.userInteractionEnabled = false
addChild(playButton)
if(ScoreCount>HighScore){
HighScore = ScoreCount
let HighscoreDefault = NSUserDefaults.standardUserDefaults()
HighscoreDefault.setInteger(HighScore, forKey: "Highscore")
}
LeaderBoardScore.text = "\(ScoreCount)"
LeaderBoardHighscore.text = "\(HighScore)"
LeaderBoardHighscore.position = CGPoint(x: frame.midX+30 , y: frame.midY+5)
LeaderBoardHighscore.xScale = 2.0
LeaderBoardHighscore.yScale = 2.0
LeaderBoardHighscore.zPosition = 15.0
LeaderBoardHighscore.fontColor = UIColor.purpleColor()
LeaderBoardScore.position = CGPoint(x: frame.midX+60 , y: frame.midY+72)
LeaderBoardScore.fontColor = UIColor.purpleColor()
LeaderBoardScore.xScale = 2.0
LeaderBoardScore.zPosition = 15.0
LeaderBoardScore.yScale = 2.0
addChild(LeaderBoardHighscore)
addChild(LeaderBoardScore)
Scores.xScale = 2
Scores.yScale = 2
Scores.zPosition = 11.0
Scores.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(Scores)
CheckGameState = true
}
}
}
func addShark(){
Player.physicsBody?.collisionBitMask = PhysicsCatagory.shark
Player.physicsBody?.contactTestBitMask = PhysicsCatagory.shark
Player.name = "Player"
Player.physicsBody?.dynamic = true
Player.physicsBody?.affectedByGravity = false
let randomNumShark = arc4random_uniform(2)
if(randomNumShark == 1){
let shark = SKSpriteNode(imageNamed: "shark_1.png")
shark.position.x = frame.size.width
let PositionY = arc4random_uniform(UInt32(frame.size.height))
shark.position.y = CGFloat(PositionY)
addChild(shark)
let sharkGoForward = SKAction.moveToX(CGFloat(-1100), duration: 1.5)
shark.runAction(sharkGoForward)
shark.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: shark.size.width, height:shark.size.height))
shark.physicsBody?.categoryBitMask = PhysicsCatagory.Player
shark.physicsBody?.contactTestBitMask = PhysicsCatagory.Player
shark.physicsBody?.collisionBitMask = PhysicsCatagory.Player
shark.physicsBody?.dynamic = true
shark.physicsBody?.affectedByGravity = false
shark.name = "shark"
shark.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(TextureArray2, timePerFrame: 0.05)))
}
}
func addJellyfish(){
Player.physicsBody?.collisionBitMask = PhysicsCatagory.jellyfish
Player.physicsBody?.contactTestBitMask = PhysicsCatagory.jellyfish
Player.name = "Player"
Player.physicsBody?.dynamic = true
Player.physicsBody?.affectedByGravity = false
let randomNumJelly = arc4random_uniform(2)
if(randomNumJelly == 1){
let jellyfish = SKSpriteNode(imageNamed: "jellyfish")
jellyfish.position.y = 0
let PositionX = arc4random_uniform(UInt32(frame.size.width))
jellyfish.position.x = CGFloat(PositionX)
addChild(jellyfish)
let jellyfishGoUp = SKAction.moveToY(CGFloat(frame.size.height+100), duration: 2.0)
jellyfish.runAction(jellyfishGoUp)
jellyfish.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: jellyfish.size.width, height:jellyfish.size.height))
jellyfish.physicsBody?.categoryBitMask = PhysicsCatagory.Player
jellyfish.physicsBody?.contactTestBitMask = PhysicsCatagory.Player
jellyfish.physicsBody?.collisionBitMask = PhysicsCatagory.Player
jellyfish.physicsBody?.dynamic = true
jellyfish.physicsBody?.affectedByGravity = false
jellyfish.name = "jellyfish"
jellyfish.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(TextureArray3, timePerFrame: 0.05)))
}
}
func timer(){
if(game == true){
ScoreCount++
myLabel.text = "\(ScoreCount)"
}
}
func rePositionPlayer(){
Player.removeFromParent()
Player.position = CGPoint(x: 80, y: 220)
addChild(Player)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in (touches ) {
let location = touch.locationInNode(self)
if(game == false){
if playButton.containsPoint(location){
game = true
LeaderBoardHighscore.removeFromParent()
LeaderBoardScore.removeFromParent()
playButton.removeFromParent()
Scores.removeFromParent()
CheckGameState = false
rePositionPlayer()
ScoreCount = 0
fishYpos = 220
}
}
if(game == true){
}
}
}
override func update(currentTime: CFTimeInterval) {
}
}
My error is at the line
let secondbody = contact.bodyB as! SKSpriteNode
It says
can cast SKPhysicsBody to unrealted SKSpriteNode
How to fix this issue?
Try saying let secondbody.node = contact.bodyB as! SKSpriteNode

didBeginContact not working in Swift 2 + SpriteKit

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

Swift - how to fix when adding a Physics Body removes sprite node from scene

I'm fairly new to programming and can't seem to figure out this Physics World issue. When I add a physics body to my sprite node, i can no longer see the sprite node in the scene.
Code:
func createBird() {
let randomSpawn = Int(arc4random_uniform(2))
if randomSpawn == 1 {
let newX = Int(-20)
let newY = Int(arc4random_uniform(500) + 300)
var p = CGPoint(x: newX, y: newY)
var destination = CGPoint(x:Int(self.frame.width+21), y:newY)
var moverSpeed = Int(arc4random_uniform(5) + 3)
let birdRight = SKSpriteNode (imageNamed: "bird-right1")
birdRight.xScale = 0.6
birdRight.yScale = 0.6
birdRight.position = p
birdRight.zPosition = 2
//birdRight.physicsBody = SKPhysicsBody(rectangleOfSize: birdRight.size)
birdRight.physicsBody?.dynamic = true
birdRight.physicsBody?.categoryBitMask = birdCategory
birdRight.physicsBody?.contactTestBitMask = ballCategory
birdRight.physicsBody?.collisionBitMask = 0
let birdMoveRight = SKAction.animateWithTextures([
SKTexture(imageNamed: "bird-right1"),
SKTexture(imageNamed: "bird-right2"),
SKTexture(imageNamed: "bird-right3"),
SKTexture(imageNamed: "bird-right4"),
SKTexture(imageNamed: "bird-right5"),
SKTexture(imageNamed: "bird-right6"),
SKTexture(imageNamed: "bird-right7"),
SKTexture(imageNamed: "bird-right8"),
SKTexture(imageNamed: "bird-right9"),
SKTexture(imageNamed: "bird-right10")
], timePerFrame: 0.05)
let foreverAction = SKAction.repeatActionForever(birdMoveRight)
birdRight.runAction(foreverAction)
let duration = NSTimeInterval(moverSpeed)
let action = SKAction.moveTo(destination, duration: duration)
birdRight.runAction(action)
addChild(birdRight)
}
else {
let newX = Int(self.frame.width+20)
let newY = Int(arc4random_uniform(500) + 300)
var p = CGPoint(x: newX, y: newY)
var destination = CGPoint(x:-21, y:newY)
var moverSpeed = Int(arc4random_uniform(5) + 3)
let birdLeft = SKSpriteNode(imageNamed: "bird-left1")
birdLeft.xScale = 0.6
birdLeft.yScale = 0.6
birdLeft.position = p
birdLeft.zPosition = 2
let birdMoveLeft = SKAction.animateWithTextures([
SKTexture(imageNamed: "bird-left1"),
SKTexture(imageNamed: "bird-left2"),
SKTexture(imageNamed: "bird-left3"),
SKTexture(imageNamed: "bird-left4"),
SKTexture(imageNamed: "bird-left5"),
SKTexture(imageNamed: "bird-left6"),
SKTexture(imageNamed: "bird-left7"),
SKTexture(imageNamed: "bird-left8"),
SKTexture(imageNamed: "bird-left9"),
SKTexture(imageNamed: "bird-left10")
], timePerFrame: 0.05)
birdLeft.physicsBody = SKPhysicsBody(rectangleOfSize: birdLeft.size)
birdLeft.physicsBody?.dynamic = false
birdLeft.physicsBody?.categoryBitMask = birdCategory
birdLeft.physicsBody?.contactTestBitMask = ballCategory
birdLeft.physicsBody?.collisionBitMask = 0
let foreverAction = SKAction.repeatActionForever(birdMoveLeft)
birdLeft.runAction(foreverAction)
let duration = NSTimeInterval(moverSpeed)
let action = SKAction.moveTo(destination, duration: duration)
birdLeft.runAction(action)
addChild(birdLeft)
}
}
Maybe it is affected by gravity and get dragged all the way down before you even see the object on your screen?
Try this:
birdRight.physicsBody?.affectedByGravity = false