Swift/SpriteKit Collision with Custom Class - ios

I have a class that creates variables for multiple SpriteNods which looks like this:
class Enemy {
var speed:Float = 0.0
var guy:SKSpriteNode
var currentFrame = 0
var randomFrame = 0
var moving = false
var rotationSpeed:CGFloat = 1.0
var angle = 0.0
var range = 1.2
var yPos = CGFloat()
var rotationDirection:Int = 0
var preLocation:CGFloat = 0
var health:Int = 0
init(speed:Float, guy:SKSpriteNode, rotationSpeed:CGFloat, rotationDirection:Int, preLocation:CGFloat, health:Int) {
self.speed = speed
self.guy = guy
self.rotationSpeed = rotationSpeed
self.rotationDirection = rotationDirection
self.preLocation = preLocation
self.health = health
}
A SpriteNode is then applied to the Enemy like this:
func addEnemy(#named: String, speed:Float, yPos: CGFloat, rotationSpeed:CGFloat, rotationDirection:Int, preLocation:CGFloat, health:Int) {
var enemyNode = SKSpriteNode(imageNamed: named)
enemyNode.physicsBody = SKPhysicsBody(texture: enemyNode.texture, alphaThreshold: 0, size: enemyNode.size)
enemyNode.physicsBody!.affectedByGravity = false
enemyNode.physicsBody!.categoryBitMask = ColliderType.Enemy.rawValue
enemyNode.physicsBody!.contactTestBitMask = ColliderType.Hero.rawValue | ColliderType.Enemy.rawValue
enemyNode.physicsBody!.collisionBitMask = ColliderType.Hero.rawValue | ColliderType.Enemy.rawValue
enemyNode.physicsBody?.allowsRotation = false
var enemy = Enemy(speed: speed, guy: enemyNode, rotationSpeed: rotationSpeed, rotationDirection: rotationDirection, preLocation: preLocation, health: health)
enemys.append(enemy)
enemy.guy.name = named
resetEnemy(enemyNode, yPos: yPos)
enemy.yPos = enemyNode.position.y
addChild(enemyNode)
}
Now i have the problem that in the didBeginContact function i only get the SpriteNodes back so i can't get to the enemy specific variables, like health.
So i want to know how i can reference the enemy class to the spritenode, so i can use it in the didBeginContact function.
I hope someone can help me. Thanks.

I just ran into this exact problem. You need to cast the node as the object you are looking for. In didBeginContact it would be something like this:
if let myEnemy = contact.bodyA.node as? Enemy {
myEnemy.speed = 99
}

Related

Load some private var on switch condition

I'm making a simple iOS game, and I have some problems.
Indeed, I created my different classes for my elements : planet, bullet, background, and asteroids.
However when I try to initialize them on switch condition (from the GameScene), I have the error message "expected declaration".
The variable "lvlSelected", is global and represents the level asked by the player (from an other scene).
Here's my switch code :
switch lvlSelected {
case 1 :
private var planet = Planet(imageName: "Planet1")
private var bullet = Bullet(imageName: "Bullet1")
private var background = Background(imageName: "Background1")
private var asteroide = Asteroides(img: "Asteroid1")
case 2 :
private var planet = Planet(imageName: "Planet2")
private var bullet = Bullet(imageName: "Bullet2")
private var background = Background(imageName: "Background2")
private var asteroide = Asteroides(img: "Asteroid2")
default :
private var planet = Planet(imageName: "Planet")
private var bullet = Bullet (imageName: "Bullet")
private var background = Background(imageName : "Background")
private var asteroide = Asteroides(img."Asteroid")
}
Thanks for your help
Here's my Planet's class :
class Planet:SKSpriteNode {
init(imageName: String){
let texture = SKTexture(imageNamed : imageName)
super.init(texture: texture, color: .clear, size: texture.size())
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width/2, center: self.anchorPoint)
self.physicsBody!.affectedByGravity = false
self.physicsBody!.categoryBitMask = GameScene.physicsCategories.planet
self.physicsBody!.collisionBitMask = GameScene.physicsCategories.none
self.physicsBody!.contactTestBitMask = GameScene.physicsCategories.asteroid
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addPlanet(parent: GameScene) {
self.setScale(0.55)
self.position = CGPoint(x: parent.size.width / 2, y: -self.size.height)
self.zPosition = 2
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
parent.addChild(self)
}
This should be the way you want.
private var planet = Planet(imageName: "Planet")
private var bullet = Bullet (imageName: "Bullet")
private var background = Background(imageName : "Background")
private var asteroide = Asteroides(img."Asteroid")
switch lvlSelected {
case 1 :
planet = Planet(imageName: "Planet1")
bullet = Bullet(imageName: "Bullet1")
background = Background(imageName: "Background1")
asteroide = Asteroides(img: "Asteroid1")
break
case 2 :
planet = Planet(imageName: "Planet2")
bullet = Bullet(imageName: "Bullet2")
background = Background(imageName: "Background2")
asteroide = Asteroides(img: "Asteroid2")
break
default :
break
}
If you declare a var inside a switch case will be available inside that case only.
There is no need for a switch in your case, you can use string interpolation:
class GameScene : SKScene
{
private let planet : Planet
private let bullet : Bullet
private let background : Background
private let asteroide : Asteroides
convenience init(lvlSelected : Int){
let level = 1 ... 2 ~= lvlSelected ? "\(lvlSelected)" : ""
planet = Planet(imageName: "Planet\(level)")
bullet = Bullet (imageName: "Bullet\(level)")
background = Background(imageName: "Background\(level)")
asteroid = Asteroides(img: "Asteroid\(level)")
self.init() //whatever init you use here
}
}
~= is the pattern match operator, and #a ... #b means range of numbers between a and b including a and b, so you are asking if a number is in a certain range
(condition) ? (statement 1) : (statement 2) is the ternary operator which is if condition true then statement 1 else statement 2
"\(var)" is string interpolation that tells the string to inject the value of var into the string

detecting if a spritenode exists in swift

I am trying to detect if one of the nodes that I have made through a subclass of SKNode (called Achievements) exists and if it doesn't exist then i'm trying to turn off a boolean variable.
What I use to locate the SKShapeNode (called "Indicator")
func checkIndicatorStatus() {
moveableArea.enumerateChildNodes(withName: "Achievement") {
(node, stop) in
let Indicate = node
Indicate.enumerateChildNodes(withName: "Indicator") {
node, stop in
if let Achievement = node as? Achievements {
menuAchieveNotificationOn = false
}
}
}
}
I have enumerated through the nodes specifically and tried searching for it but it doesn't seem to do anything. what am I doing wrong?
Here is my subclass. I have many of them named achievement displayed in my scene.
class Achievements: SKNode {
//Nodes used throughout the SKNode class
var achievementLabel = SKLabelNode()
var achievementTitleLabel = SKLabelNode()
var achievementNode = SKSpriteNode()
var notifyCircle = SKShapeNode()
//Amount Variables used as Achievement Properties
var image: String = ""
var information: String = ""
var title: String = ""
var amount = 0
var neededAmount = 0
var notification:Bool = false
var stage = 0
func getachievementData(AchName: String) {
let getDataRequest:NSFetchRequest<Achievement> = Achievement.fetchRequest()
getDataRequest.predicate = NSPredicate(format: "theSearchName == %#" , AchName)
do {
let searchResults = try CoreDatabaseContoller.getContext().fetch(getDataRequest)
//print("number of results: \(searchResults.count)")
for result in searchResults as [Achievement] {
title = result.theName!
information = result.theDescription!
image = result.theImage!
amount = Int(result.aAmount!)
neededAmount = Int(result.aNeededAmount!)
stage = Int(result.aStage!)
if result.aHasBeenAchieved!.intValue == 1 {
notification = true
}
}
}
catch {
print("ERROR: \(error)")
}
createAchievement()
}
func createAchievement() {
let tex:SKTexture = SKTexture(imageNamed: image)
achievementNode = SKSpriteNode(texture: tex, color: SKColor.black, size: CGSize(width: 85, height: 85)) //frame.maxX / 20, height: frame.maxY / 20))
achievementNode.zPosition = -10
achievementSprites.append(achievementNode)
self.name = "Achievement"
self.addChild(achievementNode)
self.zPosition = -11
createAchievementLabels()
}
func createAchievementLabels() {
achievementTitleLabel = SKLabelNode(fontNamed: "Avenir-Black")
achievementTitleLabel.fontColor = UIColor.black;
achievementTitleLabel.fontSize = 15 //self.frame.maxY/30
achievementTitleLabel.position = CGPoint (x: 0, y: 50)
achievementTitleLabel.text = "\(title)"
achievementTitleLabel.zPosition = -9
addChild(achievementTitleLabel)
achievementLabel = SKLabelNode(fontNamed: "Avenir-Black")
achievementLabel.fontColor = UIColor.black;
achievementLabel.fontSize = 13 //self.frame.maxY/30
achievementLabel.position = CGPoint (x: 0, y: -55)
achievementLabel.text = ("\(amount) / \(neededAmount)")
achievementLabel.zPosition = -9
addChild(achievementLabel)
if notification == true {
notifyCircle = SKShapeNode(circleOfRadius: 10)
notifyCircle.fillColor = .red
notifyCircle.position = CGPoint(x: 30 , y: 35)
notifyCircle.zPosition = 1000
notifyCircle.name = "Indicator"
addChild(notifyCircle)
}
}
}
EDIT 1
As you can see from the image below, there are a number of different achievement nodes each with their individual names and unlock criteria, when an achievement becomes unlocked it makes an indicator and changes the graphic, which is seen for the two X nodes here with the coloured red circle in the top right corners of each of them which is the "indicator" (if you look at the subclass at the bottom of it the creation of the indicator is there)
Now as you can seen the big red button in the bottom right hand corner of the picture is the achievement menu button which also has an indicator which is controlled by the bool variable (menuAchieveNotificationOn) what i'm trying to achieve is once the achievements with the indicators have each been pressed they are removed from the node.
what i'm trying to do is search each of the nodes to see if the indicator still exists if not I want to turn the variable (menuAchieveNotificationOn) to false.
You should be able to use this:
if let indicatorNode = childNode(withName: "//Indicator") as! SKShapeNode? {
menuAchieveNotificationOn = false
} else {
menuAchieveNotificationOn = true
}
EDIT: to run some code for EVERY "indicator" node in the scene. If any are found, achievementsFound is set to true:
achievementsFound = false
enumerateChildNodes(withName: "//Indicator") { indicatorNode, _ in
// Do something with indicatorNode
achievementsFound = true
}
Although this seems too simple, so I might have misunderstood your aim.

How do I increment and save a int value in Swift?

Im trying to keep track of how many times the user loses in my game. So for every loss it goes up by 1. I also want to save it too so the user could see how many total times they lost. Right now the code I have it works the first time and goes to one but if I lose in the game after that it just stays at 1. What am I doing wrong? Thanks!
class level1: SKScene, SKPhysicsContactDelegate, GKGameCenterControllerDelegate {
var deathScore = 0
override func didMoveToView(view: SKView) {
var deathLabel = SKLabelNode()
deathLabel = SKLabelNode(fontNamed: "LadyIce-3D")
deathLabel.text = "100"
deathLabel.zPosition = 14
deathLabel.fontSize = 100
deathLabel.fontColor = SKColor.darkTextColor()
deathLabel.position = CGPointMake(self.size.width / 1.1, self.size.height / 1.4)
deathLabel.hidden = true
self.addChild(deathLabel)
}
if firstBody.categoryBitMask == HeroCategory && fourthBody.categoryBitMask == GameOverCategory {
deathScore++
deathLabel.hidden = false
let defaults = NSUserDefaults()
let saveDeaths = NSUserDefaults().integerForKey("saveNumberOfDeaths")
if(deathScore > saveDeaths)
{
NSUserDefaults().setInteger(saveDeaths, forKey: "saveNumberOfDeaths")
}
var showNumberOfDeaths = defaults.integerForKey("saveNumberOfDeaths")
deathLabel.text = String(showNumberOfDeaths)
}
}
You are declaring a new var deathScore everytime, initialized with 0 and incrementing it. It will always be 1.
UserDefaults.standard.set(UserDefaults.standard.integer(forKey: "saveNumberOfDeaths")+1, forKey: "saveNumberOfDeaths")
deathLabel.text = String(UserDefaults.standard.integer(forKey: "saveNumberOfDeaths"))

How do I make my enemySprite respawn as new bad guy once its been killed?

I am having trouble with my game, I've managed to have my enemySprites all shoot at the hero in a synchronized matter and I've gotten them to play the "killed" animation once they've been hit. Although I've run into a rather small matter which I was really hoping you guys could help me with. The problem I have is that when my badGuy is killed they move off the screen and I don't know how I can program it so that a 'new' badGuy appears forever until the Hero sprite is killed.
This is my function to spawn my enemy:
func spawnEnemy(targetSprite: SKNode) -> SKSpriteNode {
if !gamePaused{
// create a new enemy sprite
let main = GameScene()
newEnemy = SKSpriteNode(imageNamed:"BNG1_1.png")
enemySprite.append(newEnemy)//ADD TO THE LIBRARY OF BADGUYS
newEnemy.xScale = 1.2
newEnemy.yScale = 0.6
newEnemy.physicsBody?.dynamic = true
newEnemy.physicsBody = SKPhysicsBody(texture: newEnemy.texture, size: newEnemy.size)
newEnemy.physicsBody?.affectedByGravity = false
newEnemy.physicsBody?.categoryBitMask = BodyType.badguyCollision.rawValue
newEnemy.physicsBody?.contactTestBitMask = BodyType.beamCollison.rawValue
newEnemy.physicsBody?.collisionBitMask = 0x0
let muv : UInt32 = (200 + (arc4random()%500))
let actualDuration = NSTimeInterval(random(min: CGFloat(3.0), max: CGFloat(4.0)))
let randomNum = CGPoint(x:Int (muv), y:Int (arc4random()%500))
// Create the actions
var actionMove = SKAction.moveTo(randomNum, duration: NSTimeInterval(actualDuration))
newEnemy.runAction(SKAction.sequence([actionMove]))
// position new sprite at a random position on the screen
var posX = arc4random_uniform(UInt32(sizeRect.size.width))
var posY = arc4random_uniform(UInt32(sizeRect.size.height))
newEnemy.position = CGPoint(x: screenSize.width*2 + newEnemy.size.width, y: random(min: newEnemy.size.height, max: screenSize.height - newEnemy.size.height))
let atlas = SKTextureAtlas(named: "BG1.atlas")
let anime = SKAction.animateWithTextures([atlas.textureNamed("BG1_1.png"), atlas.textureNamed("BG1_2.png"),
atlas.textureNamed("BG1_3.png"),
atlas.textureNamed("BG1_2.png"),
atlas.textureNamed("BG1_1.png")], timePerFrame: 0.1)
dinoRun = SKAction.repeatActionForever(anime)
newEnemy.runAction(dinoRun)
}
return newEnemy
}
And this is my function for once they are hit (this function is called when the collisionTest between my hero's laser and the badguy is recognized):
func deadBadGuy(){
//animation
var dinoRun:SKAction
var newdes = CGPoint(x: Int(arc4random()%500), y:0)
var actionMoov = SKAction.moveTo(newdes, duration: 3)
var goaway = SKAction.removeFromParent()
let aTlas = SKTextureAtlas(named: "dedBG.atlas")
let anime = SKAction.animateWithTextures([aTlas.textureNamed("deadBG1.png"), aTlas.textureNamed("deadBG2.png"),
aTlas.textureNamed("deadBG3.png"),
aTlas.textureNamed("deadBG2.png"),
aTlas.textureNamed("deadBG1.png")], timePerFrame: 0.1)
dinoRun = SKAction.repeatActionForever(anime)
newEnemy.runAction(dinoRun)
newEnemy.runAction(SKAction.sequence([actionMoov,goaway]))
score++
self.scoreNode.text = String(score)
enemySprites.newPlace(neewEnemy)
dead = true //i created this Boolean because the sprite keeps shooting even if its dead
}
This is the way I called for the collisionTest in my program in case you need it for more information:
func didBeginContact(contact:SKPhysicsContact){
if !gamePaused {
let firstNode = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch(firstNode){
case BodyType.beamCollison.rawValue | BodyType.badguyCollision.rawValue:
deadBadGuy()
//enemySprites.spawnEnemy(sprite)
default:
print("hit")
}
Note: I tried having the func spawnEnemy being called during the collisionTest but that results in the BadGuy staying off screen shooting at my hero.
Update : I found out how to add a new enemy sprite once the other is dead all i had to do was
newEnemy.runAction(SKAction.sequence([actionMoov,goaway]), completion: {
self.addChild(self.enemySprites.spawnEnemy(sprite))
})
in the deadBadGuy function(the spawnEnemy function is in another class which I named enemySprites as a variable). However now I've run into a new issue and that is that it adds 10 enemySprites instead of one. How can I change that?
Update 2 : I figured out that issue too, I just needed to remove to dead Boolean method in the deadBadGuy function.
I found my answer and all I had to do was add this line to my deadBadGuy function and remove the dead boolean methods
newEnemy.runAction(SKAction.sequence([actionMoov,goaway]), completion: {
self.addChild(self.enemySprites.spawnEnemy(sprite))
})

PhysicsBody is nil using SpriteKit with Swift

I have a SpriteKit game I am building and I am loading a level from a multidimensional array. The loadlevel function works the first time. It does fail if I do a println of the physicsBody above the physicsBody assignment (after the initialization of the physicBody). When I remove all the tiles with removeChildrenInArray the secondtime I run load level it throws an error saying fatal error: unexpectedly found nil while unwrapping an Optional and it points to line right below the println below. And the println indicates that it is the physicsBody that is nil. In my mind there is no reason a freshly initialize PhysicsBody should ever be nil. The println prints physicsBody nil. I have no idea why the physicsBody would be nil. I am just trying to reset the level by removing all block nodes and adding new ones in the original place according to the level map.
func loadLevel() {
var levels = Levels().data
var frameSize = view.frame.size
var thisLevel = levels[currentLevel]
println("running load level")
for (rowIndex,row) in enumerate(thisLevel) {
for (colIndex,col) in enumerate(row) {
if col == 4 {
continue
}
println("COL: \(col)")
var tile = SKSpriteNode(texture: SKTexture(imageNamed: "brick_\(tileMap[col])"))
tile.name = "tile_\(rowIndex)_\(colIndex)"
tile.position.y = frameSize.height - (tile.size.height * CGFloat(rowIndex)) - (tile.size.height/2)
tile.position.x = tile.size.width * CGFloat(colIndex) + (tile.size.width/2)
var physicsBody = SKPhysicsBody(rectangleOfSize: tile.size)
tile.physicsBody = physicsBody
tile.physicsBody.affectedByGravity = false
tile.physicsBody.categoryBitMask = ColliderType.Block.toRaw()
tile.physicsBody.contactTestBitMask = ColliderType.Ball.toRaw()
tile.physicsBody.collisionBitMask = ColliderType.Ball.toRaw()
scene.addChild(tile)
tileCount++
}
}
}
Here is my ColliderType
enum ColliderType:UInt32 {
case Paddle = 1
case Block = 2
case Wall = 3
case Ball = 4
}
This is my reset function contents:
func reset() {
tileCount = 0
var removeTiles = [SKSpriteNode]()
// remove all the tiles
for child in scene.children {
var a_tile = child as SKSpriteNode
if a_tile.name.hasPrefix("tile_") {
a_tile.removeFromParent()
a_tile.name = ""
removeTiles.append(a_tile)
}
}
removeTiles.removeAll(keepCapacity: false)
ball!.position = CGPoint(x: 200, y: 200)
ballVel = CGPoint(x: 0, y: -5)
currentLevel++
loadLevel()
lost = false
won = false
}
Here is my Level structs
struct Tile {
let map = ["blue","green","purple","red"]
}
struct Levels {
let data = [
[
[4,4,0,4,0,4,0,4,0,4,0,4,0,0,4,4],
[4,4,1,4,1,4,1,4,1,4,1,4,1,1,4,4],
[4,4,2,4,2,4,2,4,2,4,2,4,2,2,4,4],
[4,4,3,4,3,4,3,4,3,4,3,4,3,3,4,4]
],
[
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[2,2,2,2,2,2,2,4,2,2,2,2,2,2,2,2],
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
]
]
}
If this is a bug in Swift I am trying to figure out a way around so I can just make this work.
Looks like SKPhysicsBody is instantiated with an empty size. Try to create the physics body object with an explicit size, like so:
var physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(100, 100))
Alternatively, you can set the size directly on the SKSpriteNode or use one of its constructors that take a CGSize construct like initWithTexture:color:size:

Resources