Swift - How to collect "diamonds", add "diamonds" to "diamonds? - ios

I am making a game that when the player collides with diamonds it will add one to the diamond score and if they play again the current diamond score will add onto the previous one. If the user closes the app I want the diamonds to remain the same and not reset.
So far, I have made the diamonds spawn and move along with the game, but when it collides it says game over. I don't want that.
Question 1 - I want to know how to make the player collide with diamond and collect it (removeFromIndex) I'm guessing, whilst adding +1 to the diamond score
Question 2 - I want to know how to make the currect diamond score add onto the overall score. So if the user has 5 diamonds and plays again and collects 4 diamonds the total diamonds the user should have is 9 diamonds
Code:
import Foundation
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var movingGround: PPMovingGround!
var square1: PPSquare1!
var wallGen: PPWallGen!
var diamondGen: PPDiamondGen!
var isStarted = false
var isGameOver = false
var lastChangedBackground = 0
var lastMovingSpeed = 0
var background = SKSpriteNode()
var playerNode: SKNode!
override func didMoveToView(view: SKView) {
//backgroundColor = UIColor.greenColor()
//backgroundColor = UIColor(red: 223/255.0, green: 86/255.0, blue: 94/255.0, alpha: 1.0)
background = SKSpriteNode(color: UIColor(red: 220/255.0, green: 220/255.0, blue: 220/255.0, alpha: 1.0), size: view.frame.size)
background.position = view.center
self.addChild(background)
playerNode = SKNode()
// playerNode.position = CGPointMake(40, 200)
addChild(playerNode)
addMovingGround()
addSquare1()
addEffect()
addDiamondGen()
addWallGen()
addTapToStartLabel()
addDiamondsLabels()
addPointsLabels()
addPhysicsWorld()
loadHighscore()
}
func addMovingGround() {
movingGround = PPMovingGround(size: CGSizeMake(view!.frame.width, kMLGroundHeight))
movingGround.position = CGPointMake(0, view!.frame.size.height/2)
addChild(movingGround)
}
func addSquare1() {
square1 = PPSquare1()
square1.position = CGPointMake(70, movingGround.position.y + movingGround.frame.size.height/2 + square1.frame.size.height/2)
square1.zPosition = 1
playerNode.addChild(square1)
}
func addEffect() {
var playerTrailPath = NSBundle.mainBundle().pathForResource("sparks", ofType: "sks")!
var playerTrail = NSKeyedUnarchiver.unarchiveObjectWithFile(playerTrailPath) as! SKEmitterNode
playerTrail.name = "playerTrail"
playerTrail.position = CGPointMake(-30, -20)
square1.addChild(playerTrail)
}
func addDiamondGen() {
diamondGen = PPDiamondGen(color: UIColor.clearColor(), size: view!.frame.size)
diamondGen.position = view!.center
addChild(diamondGen)
}
func addWallGen() {
wallGen = PPWallGen(color: UIColor.clearColor(), size: view!.frame.size)
wallGen.position = view!.center
addChild(wallGen)
}
func addTapToStartLabel() {
let tapToStartLabel = SKLabelNode(text: "Tap to start!")
tapToStartLabel.name = "tapToStartLabel"
tapToStartLabel.position.x = view!.center.x
tapToStartLabel.position.y = view!.center.y + 40
tapToStartLabel.fontColor = UIColor.whiteColor()
tapToStartLabel.fontName = "Helvetica"
tapToStartLabel.fontSize = 22.0
addChild(tapToStartLabel)
}
func addDiamondsLabels() {
let diamondsLabel = PPDiamondsLabel(num: 0)
diamondsLabel.name = "diamondPointsLabel"
diamondsLabel.alpha = 0.50
diamondsLabel.position.x = view!.center.x
diamondsLabel.position.y = view!.center.y + 120
diamondsLabel.fontColor = UIColor.whiteColor()
diamondsLabel.fontName = "Helvetica"
diamondsLabel.fontSize = 40
addChild(diamondsLabel)
let diamondTotalLabel = PPDiamondsLabel(num: 0)
diamondTotalLabel.name = "diamondHighscoreLabel"
diamondTotalLabel.alpha = 0.50
diamondTotalLabel.position = CGPointMake(view!.frame.size.width - 40, view!.frame.size.height - 30)
diamondTotalLabel.fontColor = UIColor.whiteColor()
diamondTotalLabel.fontName = "Helvetica"
diamondTotalLabel.fontSize = 24
addChild(diamondTotalLabel)
let diamondTotalTextLabel = SKLabelNode(text: "Diamonds: ")
diamondTotalTextLabel.alpha = 0.95
diamondTotalTextLabel.fontColor = UIColor.whiteColor()
diamondTotalTextLabel.fontSize = 22.0
diamondTotalTextLabel.fontName = "Helvetica"
diamondTotalTextLabel.position = CGPointMake(-90.0,2.0)
diamondTotalLabel.addChild(diamondTotalTextLabel)
}
func addPointsLabels() {
let pointsLabel = PPPointsLabel(num: 0)
pointsLabel.name = "pointsLabel"
pointsLabel.alpha = 0.50
pointsLabel.position.x = view!.center.x
pointsLabel.position.y = view!.center.y + 120
pointsLabel.fontColor = UIColor.whiteColor()
pointsLabel.fontName = "Helvetica"
pointsLabel.fontSize = 40
addChild(pointsLabel)
let highscoreLabel = PPPointsLabel(num: 0)
highscoreLabel.name = "highscoreLabel"
highscoreLabel.alpha = 0.50
highscoreLabel.position = CGPointMake(view!.frame.size.width - 40, view!.frame.size.height - 30)
highscoreLabel.fontColor = UIColor.whiteColor()
highscoreLabel.fontName = "Helvetica"
highscoreLabel.fontSize = 24
addChild(highscoreLabel)
let highscoreTextLabel = SKLabelNode(text: "Highscore: ")
highscoreTextLabel.alpha = 0.95
highscoreTextLabel.fontColor = UIColor.whiteColor()
highscoreTextLabel.fontSize = 22.0
highscoreTextLabel.fontName = "Helvetica"
highscoreTextLabel.position = CGPointMake(-90.0,2.0)
highscoreLabel.addChild(highscoreTextLabel)
}
func addPhysicsWorld() {
physicsWorld.contactDelegate = self
}
func loadHighscore() {
let defaults = NSUserDefaults.standardUserDefaults()
let highscoreLabel = childNodeWithName("highscoreLabel") as! PPPointsLabel
highscoreLabel.setTo(defaults.integerForKey("highscore"))
}
func start() {
isStarted = true
let tapToStartLabel = childNodeWithName("tapToStartLabel")
tapToStartLabel?.removeFromParent()
square1.stop()
movingGround.start()
wallGen.startGenWallsEvery(1)
diamondGen.startGenDiamondsEvery(1)
}
// MARK - Game Lifecycle
func gameOver() {
isGameOver = true
// everything stops
square1.fall()
wallGen.stopWalls()
diamondGen.stopDiamonds()
movingGround.stop()
square1.stop()
// create game over label
let gameOverLabel = SKLabelNode(text: "Game Over!")
gameOverLabel.fontColor = UIColor.whiteColor()
gameOverLabel.fontName = "Helvetica"
gameOverLabel.position.x = view!.center.x
gameOverLabel.position.y = view!.center.y + 80
gameOverLabel.fontSize = 22.0
addChild(gameOverLabel)
// save current points label value
let pointsLabel = childNodeWithName("pointsLabel") as! PPPointsLabel
let highscoreLabel = childNodeWithName("highscoreLabel") as! PPPointsLabel
let diamondsPointsLabel = childNodeWithName("diamondPointsLabel") as! PPDiamondsLabel
let diamondHighscoreLabel = childNodeWithName("diamondHighscoreLabel") as! PPDiamondsLabel
if highscoreLabel.number < pointsLabel.number {
highscoreLabel.setTo(pointsLabel.number)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(highscoreLabel.number, forKey: "highscore")
}
}
func restart() {
let newScence = GameScene(size: view!.bounds.size)
newScence.scaleMode = .AspectFill
view!.presentScene(newScence)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if isGameOver {
restart()
} else if !isStarted {
start()
} else {
square1.flip()
}
}
override func update(currentTime: CFTimeInterval) {
if wallGen.wallTrackers.count > 0 {
let wall = wallGen.wallTrackers[0] as PPWall
let wallLocation = wallGen.convertPoint(wall.position, toNode: self)
if wallLocation.x < square1.position.x {
wallGen.wallTrackers.removeAtIndex(0)
let pointsLabel = childNodeWithName("pointsLabel") as! PPPointsLabel
pointsLabel.increment()
if pointsLabel.number % 10 == 0 {
kDefaultXToMovePerSecond == kDefaultXToMovePerSecond + 50
}
else if (pointsLabel.number % 20 == 0) {
kDefaultXToMovePerSecond == kDefaultXToMovePerSecond + 50
}
else if (pointsLabel.number % 30 == 0) {
kDefaultXToMovePerSecond == kDefaultXToMovePerSecond + 50
}
else if (pointsLabel.number % 40 == 0) {
kDefaultXToMovePerSecond == kDefaultXToMovePerSecond + 50
}
else if (pointsLabel.number % 50 == 0) {
kDefaultXToMovePerSecond == kDefaultXToMovePerSecond + 50
}
else if (pointsLabel.number % 60 == 0) {
kDefaultXToMovePerSecond == kDefaultXToMovePerSecond + 50
}
else if (pointsLabel.number % 70 == 0) {
kDefaultXToMovePerSecond == kDefaultXToMovePerSecond + 50
}
else if (pointsLabel.number % 80 == 0) {
kDefaultXToMovePerSecond == kDefaultXToMovePerSecond + 50
}
if pointsLabel.number % 10 == 0 && pointsLabel.number != lastChangedBackground{
lastChangedBackground = pointsLabel.number
if (lastChangedBackground == 10) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 164/255, green: 200/255, blue: 237/255, alpha: 1), colorBlendFactor: 0.1, duration: 1)) //light blue
}
else if (lastChangedBackground == 20) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 237/255, green: 164/255, blue: 236/255, alpha: 1), colorBlendFactor: 0.1, duration: 1)) //light purple
}
else if (lastChangedBackground == 30) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 164/255, green: 237/255, blue: 165/255, alpha: 1), colorBlendFactor: 0.1, duration: 1)) //light green
}
else if (lastChangedBackground == 40) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 237/255, green: 164/255, blue: 164/255, alpha: 1), colorBlendFactor: 0.1, duration: 1)) //light red
}
else if (lastChangedBackground == 50) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 000/255, green: 000/255, blue: 000/255, alpha: 1), colorBlendFactor: 0.1, duration: 1)) //black
}
else if (lastChangedBackground == 60) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 000/255, green: 128/255, blue: 255/255, alpha: 1), colorBlendFactor: 0.1, duration: 1)) // ultra blue
}
else if (lastChangedBackground == 70) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 88/255, green: 201/255, blue: 50/255, alpha: 1), colorBlendFactor: 0.1, duration: 1)) //ultra green
}
else if (lastChangedBackground == 80) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 245/255, green: 221/255, blue: 39/255, alpha: 1), colorBlendFactor: 0.1, duration: 1)) // ultra yellow
}
else if (lastChangedBackground == 90) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 245/255, green: 221/255, blue: 39/255, alpha: 1), colorBlendFactor: 0.1, duration: 1))
}
else if (lastChangedBackground == 100) {
background.runAction(SKAction.colorizeWithColor(UIColor(red: 245/255, green: 221/255, blue: 39/255, alpha: 1), colorBlendFactor: 0.1, duration: 1))
}
}
}
}
}
// MARK: - SKPhysicsContactDelegate
func didBeginContact(contact: SKPhysicsContact) {
if !isGameOver {
gameOver()
}
}
Thanks in advance!

Related

How to animate GMSMarker?

How i can perform animation like this in GMSMarker?
I tried to add layer to GMSMarker layer but it doesn't work..
let pulse = Pulsing(center: CGPoint(x: 240, y: 480),radius: 36, fillColor: #colorLiteral(red: 0.9979501367, green: 0.7617542744, blue: 0.05507106334, alpha: 0.5), strokeColor: #colorLiteral(red: 0.9979501367, green: 0.7617542744, blue: 0.05507106334, alpha: 1), lineWidth: 1)
pulse.animationDuration = 0.8
fromLoctionMarker.layer.addSublayer(pulse)
I just created five circles
and lunch timer for every circle and animate circle border circle opacity color and circle radius changing smoothly using timer
use recursive to make the animation infinity
// marker animation variables
private var numberOfCircels = 0
private var circlesTimers = [Timer]()
private var circlesRadius = [Int]()
private var circlesColors = [CGFloat]()
private var circlesBorderColors = [CGFloat]()
private var gmsCircles = [[GMSCircle]]()
private func createCircel(){
if numberOfCircels == 5 { return }
let tempNumberOfCircels = numberOfCircels
let circleTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timerFiredForCircel), userInfo: ["currentIndex": tempNumberOfCircels], repeats: true)
circlesTimers.append(circleTimer)
circlesRadius.append(0)
gmsCircles.append([GMSCircle]())
circlesColors.append(0.2)
circlesBorderColors.append(0.7)
numberOfCircels = numberOfCircels + 1
print(numberOfCircels, "numberOfCircels")
}
#objc
private func timerFiredForCircel(timer: Timer){
guard let context = timer.userInfo as? [String: Int] else { return }
guard let currentIndex = context["currentIndex"] else { return }
let location = order.fromLocation.location
let circel = GMSCircle(position: location, radius: CLLocationDistance(circlesRadius[currentIndex]))
circel.fillColor = #colorLiteral(red: 1, green: 0.7607843137, blue: 0.05882352941, alpha: 1).withAlphaComponent(circlesColors[currentIndex])
circel.strokeColor = #colorLiteral(red: 1, green: 0.7607843137, blue: 0.05882352941, alpha: 1).withAlphaComponent(circlesBorderColors[currentIndex])
circel.strokeWidth = 1
gmsCircles[currentIndex].append(circel)
if circlesRadius[currentIndex] < 150{
circlesRadius[currentIndex] += 3
circlesColors[currentIndex] -= (0.2 / 50)
circlesBorderColors[currentIndex] -= 0.014
}else if circlesRadius[currentIndex] >= 150{
circlesRadius[currentIndex] = 0
circlesColors[currentIndex] = 0.2
circlesBorderColors[currentIndex] = 0.7
}
circel.map = googleMab
for i in 0..<gmsCircles[currentIndex].count - 1{
let circle = gmsCircles[currentIndex][i]
circle.map = nil
gmsCircles[currentIndex].removeAll(where: { $0 == circle})
}
if circlesRadius[currentIndex] == 30{
self.createCircel()
}
}

How to add an arc4random when the score is increment?

I am making a game in which there are enemies of diferente colors, I want to do that if you get to a certain score a new enemy of different color is added to the game.
how can I add another color to my arc4random func when the score is 20?(20 for example)
class GameScene: SKScene, SKPhysicsContactDelegate {
var circuloPrincipal = SKSpriteNode(imageNamed: "circulo")
var enemigoTimer = NSTimer()
var hits = 0
var colorAmarillo: UIColor = UIColor(red: 0.9, green: 0.7, blue: 0.2, alpha: 0.9)
var colorAzul = UIColor(red: 0.1, green: 0.4, blue: 0.5, alpha: 1.0)
var colorVerde: UIColor = UIColor(red: 0.3, green: 0.7, blue: 0.5, alpha: 0.9)
var scoreLabel = SKLabelNode(fontNamed: "STHeitiJ-Medium")
var score = 0
//colorAmarillo = Yellow color
//colorAzul = Blue color
//colorVerde = Green color
func colisionPrincipal(enemigo: SKSpriteNode) {
//This is when the enemy makes contact with the player
if hits < 3 && circuloPrincipal.color != enemigo.color{
circuloPrincipal.runAction(SKAction.scaleBy(1.5, duration:0.5))
enemigo.removeFromParent()
hits++
}
if scoreLabel == "20" {
//Here I want to add an enemy of another color
}
scoreLabel.removeAllActions()
}else if circuloPrincipal.color == enemigo.color {
//circuloPrincipal = player
//enemigo = enemy
//color = color
enemigo.removeFromParent()
score++
scoreLabel.text = "\(score)"
}
func enemigos() //This funciĆ³n is the arc4random to random the colors
{
let enemigo = SKSpriteNode(imageNamed: "circulo")
enemigo.size = CGSize(width: 25, height: 25)
enemigo.color = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)
enemigo.colorBlendFactor = 1.0
enemigo.zPosition = 1.0
enemigo.physicsBody = SKPhysicsBody(circleOfRadius: enemigo.size.height / 2)
enemigo.physicsBody?.categoryBitMask = physicsCategory.enemigo
enemigo.physicsBody?.contactTestBitMask = physicsCategory.circuloPrincipal
enemigo.physicsBody?.collisionBitMask = physicsCategory.circuloPrincipal
enemigo.physicsBody?.dynamic = true
enemigo.physicsBody?.affectedByGravity = true
enemigo.name = "enemigo"
}
let colorRandom = arc4random() % 3
switch colorRandom {
case 0:
enemigo.color = colorAmarillo
enemigo.colorBlendFactor = 1.0
break
case 1:
enemigo.color = colorAzul
enemigo.colorBlendFactor = 1.0
break
case 2:
enemigo.color = colorVerde
enemigo.colorBlendFactor = 1.0
break
default:
break
}
Your code and question is really messed up but maybe (just maybe) I will help you:)
First add import statement
import GameplayKit
Next - generate random enemy color
let colors = [SKColor.redColor(), SKColor.blueColor(), SKColor.greenColor()]
let randomColorIndex = GKRandomDistribution(lowestValue: 0, highestValue: colors.count - 1).nextInt()
// First solution using ternary conditional operator
enemy.color = score == 20 ? SKColor.blackColor() : colors[randomColorIndex]
// Second - using if-else clause
if score == 20 {
enemy.color = SKColor.blackColor()
} else if score == 100 {
enemy.color = SKColor.whiteColor()
} else {
enemy.color = colors[randomColorIndex]
}

Swift - How to change background color when a certain amount of points are gained

I have been working on a game that when the player gets 10 points the background will change into another color that I put in the string, the same will happen for 20 points, 30 points and so on. My question is how can I make the background fade into different colors when the player gets over 10 points /20 points /30 points. I don't want the colors to be random as I want to put my own color codes/hex values, also I don't want the colors to change when a button is pressed. I just want it to change when the player gets the over a certain amount of points.
A good example of this would be the game "Don't Touch The Spikes" every 5 points you gain the background fades into a different one.
Note: I made the game in the GameScene and not using the GameViewController as it I made the project into a game file so:
import Foundation
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var movingGround: PPMovingGround!
var hero: PPHero!
var wallGen: PPWallGen!
var isStarted = false
var isGameOver = false
override func didMoveToView(view: SKView) {
//backgroundColor = UIColor.greenColor()
backgroundColor = UIColor(red: 223/255.0, green: 86/255.0, blue: 94/255.0, alpha: 1.0)
addMovingGround()
addHero()
addWallGen()
addTapToStartLabel()
addStageLabel()
addPointsLabels()
addPhysicsWorld()
loadHighscore()
}
func addLevelLabel() {
}
func addMovingGround() {
movingGround = PPMovingGround(size: CGSizeMake(view!.frame.width, kMLGroundHeight))
movingGround.position = CGPointMake(0, view!.frame.size.height/2)
addChild(movingGround)
}
func addHero() {
hero = PPHero()
hero.position = CGPointMake(70, movingGround.position.y + movingGround.frame.size.height/2 + hero.frame.size.height/2)
addChild(hero)
}
func addWallGen() {
wallGen = PPWallGen(color: UIColor.clearColor(), size: view!.frame.size)
wallGen.position = view!.center
addChild(wallGen)
}
func addTapToStartLabel() {
let tapToStartLabel = SKLabelNode(text: "Tap to start!")
tapToStartLabel.name = "tapToStartLabel"
tapToStartLabel.position.x = view!.center.x
tapToStartLabel.position.y = view!.center.y + 40
tapToStartLabel.fontName = "Helvetica"
tapToStartLabel.fontColor = UIColor.whiteColor()
tapToStartLabel.fontSize = 22.0
addChild(tapToStartLabel)
tapToStartLabel.runAction(blinkAnimation())
}
func addStageLabel() {
let stageLabel = PPStageLabel(num: 1)
stageLabel.name = "stageLabel"
stageLabel.position.x = view!.center.x
stageLabel.position.y = view!.center.y - 120
stageLabel.fontColor = UIColor.whiteColor()
stageLabel.fontName = "Helvetica"
stageLabel.fontSize = 40
addChild(stageLabel)
let stageTextLabel = SKLabelNode(text: "Stage")
stageTextLabel.fontColor = UIColor.whiteColor()
stageTextLabel.fontSize = 14.0
stageTextLabel.fontName = "Helvetica"
stageTextLabel.position = CGPointMake(3.0,-15.0)
stageLabel.addChild(stageTextLabel) }
func addPointsLabels() {
let pointsLabel = PPPointsLabel(num: 0)
pointsLabel.name = "pointsLabel"
pointsLabel.position.x = view!.center.x
pointsLabel.position.y = view!.center.y + 120
pointsLabel.fontColor = UIColor.whiteColor()
pointsLabel.fontName = "Helvetica"
pointsLabel.fontSize = 40
addChild(pointsLabel)
let highscoreLabel = PPPointsLabel(num: 0)
highscoreLabel.name = "highscoreLabel"
highscoreLabel.position = CGPointMake(view!.frame.size.width - 40, view!.frame.size.height - 30)
highscoreLabel.fontColor = UIColor.whiteColor()
highscoreLabel.fontName = "Helvetica"
highscoreLabel.fontSize = 24
addChild(highscoreLabel)
let highscoreTextLabel = SKLabelNode(text: "Highscore: ")
highscoreTextLabel.fontColor = UIColor.whiteColor()
highscoreTextLabel.fontSize = 14.0
highscoreTextLabel.fontName = "Helvetica"
highscoreTextLabel.position = CGPointMake(-70.0,3.5)
highscoreLabel.addChild(highscoreTextLabel)
}
func addPhysicsWorld() {
physicsWorld.contactDelegate = self
}
func loadHighscore() {
let defaults = NSUserDefaults.standardUserDefaults()
let highscoreLabel = childNodeWithName("highscoreLabel") as! PPPointsLabel
highscoreLabel.setTo(defaults.integerForKey("highscore"))
}
// MARK - Game Lifecycle
func start() {
isStarted = true
let tapToStartLabel = childNodeWithName("tapToStartLabel")
tapToStartLabel?.removeFromParent()
hero.stop()
movingGround.start()
wallGen.startGenWallsEvery(1)
}
func gameOver() {
isGameOver = true
// everything stops
hero.fall()
wallGen.stopWalls()
movingGround.stop()
hero.stop()
// create game over label
let gameOverLabel = SKLabelNode(text: "Game Over!")
gameOverLabel.fontColor = UIColor.whiteColor()
gameOverLabel.fontName = "Helvetica"
gameOverLabel.position.x = view!.center.x
gameOverLabel.position.y = view!.center.y + 80
gameOverLabel.fontSize = 22.0
addChild(gameOverLabel)
gameOverLabel.runAction(blinkAnimation())
// save current points label value
let pointsLabel = childNodeWithName("pointsLabel") as! PPPointsLabel
let highscoreLabel = childNodeWithName("highscoreLabel") as! PPPointsLabel
let stageLabel = childNodeWithName("stageLabel") as! PPStageLabel
if highscoreLabel.number < pointsLabel.number {
highscoreLabel.setTo(pointsLabel.number)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(highscoreLabel.number, forKey: "highscore")
}
}
func restart() {
let newScence = GameScene(size: view!.bounds.size)
newScence.scaleMode = .AspectFill
view!.presentScene(newScence)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if isGameOver {
restart()
}else if !isStarted {
start()
}else{
hero.flip()
}
}
override func update(currentTime: CFTimeInterval) {
if wallGen.wallTrackers.count > 0 {
let wall = wallGen.wallTrackers[0] as PPWall
let wallLocation = wallGen.convertPoint(wall.position, toNode: self)
if wallLocation.x < hero.position.x {
wallGen.wallTrackers.removeAtIndex(0)
let pointsLabel = childNodeWithName("pointsLabel") as! PPPointsLabel
pointsLabel.increment()
}
}else if
wallGen.wallTrackers.count > 0 {
let wall = wallGen.wallTrackers[0] as PPWall
let wallLocation = wallGen.convertPoint(wall.position, toNode: self)
if wallLocation.x < hero.position.x {
wallGen.wallTrackers.removeAtIndex(0)
let stageLabel = childNodeWithName("stageLabel") as! PPStageLabel
stageLabel.increment()
}
}
}
// MARK: - SKPhysicsContactDelegate
func didBeginContact(contact: SKPhysicsContact) {
if !isGameOver {
gameOver()
}
}
// MARR: - Animations
func blinkAnimation() -> SKAction {
let duration = 0.4
let fadeOut = SKAction.fadeAlphaTo(0.0, duration: duration)
let fadeIn = SKAction.fadeAlphaTo(1.0, duration: duration)
let blink = SKAction.sequence([fadeOut, fadeIn])
return SKAction.repeatActionForever(blink)
}
}
I think you can't animate SKView.First Declare the variables
var isStarted = false
var isGameOver = false
var lastChangedBackground = 0
var background = SKSpriteNode()
To do what you want you could add an SKNode as child of your SKScene and let it be the background and create a variable lastChangedBackground in the didMoveToView() function. The lastChangedBackground will let the background change its color only once when it get to a certain value of points.
Then you can add to your update function something like this:
override func didMoveToView(view: SKView) {
//backgroundColor = UIColor.greenColor()
//backgroundColor = SKSpriteNode()
var background = SKSpriteNode(color: UIColor(red: 223/255.0, green: 86/255.0, blue: 94/255.0, alpha: 1.0),size: view.bounds.size)
background.position = view.center
self.addChild(background)
addMovingGround()
addHero()
addWallGen()
addTapToStartLabel()
addStageLabel()
addPointsLabels()
addPhysicsWorld()
loadHighscore()
}
override func update(currentTime: CFTimeInterval) {
if wallGen.wallTrackers.count > 0 {
let wall = wallGen.wallTrackers[0] as PPWall
let wallLocation = wallGen.convertPoint(wall.position, toNode: self)
if wallLocation.x < hero.position.x {
wallGen.wallTrackers.removeAtIndex(0)
let pointsLabel = childNodeWithName("pointsLabel") as! PPPointsLabel
pointsLabel.increment()
//Here points should receive pointsLabel value
//if pointsLabel.num % 10 == 0 then points is 10, 20, 30...
if pointsLabel.num % 10 == 0 && pointsLabel.num != lastChangedBackground{
lastChangedBackground = points
if (lastChangedBackground == 10) {
background.runAction(SKAction.colorizeWithColor(SKColor.blueColor(), colorBlendFactor: 0.5, duration: 1))
}
else if(lastChangedBackground == 20){
background.runAction(SKAction.colorizeWithColor(SKColor.greenColor(), colorBlendFactor: 0.5, duration: 1))
}
else if(lastChangedBackground == 30){
background.runAction(SKAction.colorizeWithColor(SKColor.redColor(), colorBlendFactor: 0.5, duration: 1))
}
for wall in wallGen.wallTrackers {
wall.runAction(SKAction.colorizeWithColor(background.color, colorBlendFactor: 0.5, duration: 1))
}
}
}
}else if
wallGen.wallTrackers.count > 0 {
let wall = wallGen.wallTrackers[0] as PPWall
let wallLocation = wallGen.convertPoint(wall.position, toNode: self)
if wallLocation.x < hero.position.x {
wallGen.wallTrackers.removeAtIndex(0)
let stageLabel = childNodeWithName("stageLabel") as! PPStageLabel
stageLabel.increment()
}
}
}

Issue comparing UIColors in Swift

I need to compare two UIColors, but for some reason it always return false. I tried to compare using == and .isEqual(), but neither of them seem to work.
//This is a sample of the colors I have created
let blue_color = UIColor(red: 122/255, green: 180/255, blue: 190/255, alpha: 1)
//This is the SpriteNode I have to compare
let square = SKSpriteNode(color: randomColorController(), size: ksquaresize)
randomColorController() is just a function that randomizes colors and returns it, so it is called when square is created.
func randomColorController() -> UIColor {
let random = arc4random_uniform(3) + 1
switch random {
case 1:
let color = blue_color
return color
case 2:
let color = yellow_color
return color
case 3:
let color = yellow_color
return color
default:
let color = UIColor.clearColor()
return color
}
Then, depending on the position of the square I have created it will check collision comparing the color of the square I have created and the colors I have initialized at the beginning.
func checkCollision(currentTime: CFTimeInterval, Square: SKSpriteNode) -> Int{
let color = Square.color
print(color.isEqual(blue_color))
print(color.isEqual(red_color))
print(color.isEqual(yellow_color))
if Square.position.y >= 0 && Square.position.y <= 40 {
if color.isEqual(blue_color) && (Square.position.x < basesize.width) {
// ADDS 1 POINT TO THE SCORE LABEL
flag = 1
points += 1
} else if color.isEqual(red_color) && (Square.position.x > (basesize.width*2)){
flag = 1
points += 1
} else if color.isEqual(yellow_color) && (Square.position.x < (basesize.width*2)) && (Square.position.x > basesize.width) {
flag = 1
points += 1
} else {
flag = -1
}
}
But color.isEqual(blue_color) or any of the other colors, doesn't seem to work. I have printed Square.color and blue_color (and the others), and they match. But it would always return false.
extension UIColor {
func isEqual(color: UIColor?) -> Bool {
guard let color = color else { return false }
var red:CGFloat = 0
var green:CGFloat = 0
var blue:CGFloat = 0
var alpha:CGFloat = 0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
var targetRed:CGFloat = 0
var targetGreen:CGFloat = 0
var targetBlue:CGFloat = 0
var targetAlpha:CGFloat = 0
color.getRed(&targetRed, green: &targetGreen, blue: &targetBlue, alpha: &targetAlpha)
return (Int(red*255.0) == Int(targetRed*255.0) && Int(green*255.0) == Int(targetGreen*255.0) && Int(blue*255.0) == Int(targetBlue*255.0) && alpha == targetAlpha)
}
}
I tested in swift 3, 4
You can use "==" or isEqual. I have just tested both of them and they work fine:
let redColor = UIColor.redColor()
let greenColor = UIColor.greenColor()
let blueColor = UIColor.blueColor()
let testColor = UIColor.greenColor()
println( testColor == redColor ) // false
println( testColor == greenColor ) // true
println( testColor == blueColor ) // false
println( testColor.isEqual(redColor) ) // false
println( testColor.isEqual(greenColor) ) // true
println( testColor.isEqual(blueColor) ) // false
I have just reproduced the issue only happens after extracting the SKSpriteNode color and as you said only with fraction colors. You can work your way around this issue comparing the color description as follow:
let blue_color = UIColor(red: 122/255, green: 180/255, blue: 190/255, alpha: 1)
let yellow_color = UIColor(red: 253/255, green: 213/255, blue: 123/255, alpha: 1)
let red_color = UIColor(red: 238/255, green: 116/255, blue: 71/255, alpha: 1)
func randomColorController() -> UIColor {
let random = arc4random_uniform(3) + 1
switch random {
case 1:
return blue_color
case 2:
return red_color
case 3:
return yellow_color
default:
return UIColor.clearColor()
}
}
let square = SKSpriteNode(color: randomColorController(), size: CGSize(width: 30, height: 30))
if square.color.description == blue_color.description {
println(true)
}
if square.color.description == red_color.description {
println(true)
}
if square.color.description == yellow_color.description {
println(true)
}

ScoreLabel in Swift for Game not working right

I'm trying to get a score label to work in my game, I want the score to increase by 1 whenever "hero" passes a "wall" I've got it so the number 0 is up top in the corner where the score is, and when I start the game it counts up but way too fast. As in the wall won't even be coming yet and I'm already at Example: 67 points. Any suggestions on how I can get it so that when the hero passes the wall it gives 1 point or if the wall gets to point x I get 1 point?
It's kind of like flappy bird!
Here is the code
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var movingGround: CSMovingGround!
var hero: CSHero!
var cloudGenerator: CSCloudGenerator!
var wallGenerator: CSWallGenerator!
var wall: CSWall!
var scoreLabel = UILabel()
var score = Int()
var isStarted = false
var heroCategory: UInt32 = 1<<1
var wallCategory: UInt32 = 1<<2
var groundCategory: UInt32 = 1<<2
var invisCategory: UInt32 = 1<<3
let walls = CSWall()
override func didMoveToView(view: SKView) {
backgroundColor = UIColor(red: 159.0/255.0, green: 201.0/255, blue: 244.0/255.0, alpha: 1.0)
/*
let backgroundTexture = SKTexture(imageNamed: "background.png")
let backgroundImage = SKSpriteNode(texture: backgroundTexture, size: view.frame.size)
backgroundImage.position = view.center
addChild(backgroundImage)
*/
// add ground
movingGround = CSMovingGround(size: CGSizeMake(view.frame.width, kCSGroundHeight))
movingGround.position = CGPointMake(0, view.frame.size.height/2)
self.addChild(movingGround)
// add hero
hero = CSHero()
hero.position = CGPointMake(70, movingGround.position.y + movingGround.frame.size.height/2 + hero.frame.size.height/2)
hero.physicsBody = SKPhysicsBody(rectangleOfSize: hero.size)
hero.physicsBody?.dynamic = true
hero.physicsBody?.allowsRotation = false
hero.physicsBody!.collisionBitMask = heroCategory | wallCategory
hero.physicsBody!.contactTestBitMask = wallCategory | heroCategory | groundCategory
self.addChild(hero)
hero.breathe()
// add cloud generator
cloudGenerator = CSCloudGenerator(color: UIColor.clearColor(), size: view.frame.size)
cloudGenerator.position = view.center
addChild(cloudGenerator)
cloudGenerator.populate(7)
cloudGenerator.startGeneratingWithSpawnTime(5)
// add wall generator
wallGenerator = CSWallGenerator(color: UIColor.clearColor(), size: view.frame.size)
wallGenerator.position = view.center
wallGenerator.physicsBody = SKPhysicsBody(edgeLoopFromRect : wallGenerator.frame)
wallGenerator.physicsBody?.dynamic = false
wallGenerator.physicsBody?.categoryBitMask = wallCategory
wallGenerator.physicsBody!.collisionBitMask = wallCategory | heroCategory | invisCategory
wallGenerator.physicsBody!.contactTestBitMask = invisCategory
self.addChild(wallGenerator)
let ground1 = SKSpriteNode(color: UIColor.clearColor(), size: CGSizeMake(view.frame.size.width, 20))
ground1.position = view.center
ground1.physicsBody = SKPhysicsBody(rectangleOfSize: ground1.size)
ground1.physicsBody!.dynamic = false
ground1.physicsBody!.affectedByGravity = false
ground1.physicsBody!.categoryBitMask = groundCategory
ground1.physicsBody!.collisionBitMask = groundCategory | heroCategory
self.addChild(ground1)
let ground2 = SKSpriteNode(color: UIColor.blackColor(), size: CGSizeMake(view.frame.size.width, 20))
ground2.position = CGPointMake(284, 98)
ground2.physicsBody = SKPhysicsBody(rectangleOfSize: ground2.size)
ground2.physicsBody!.dynamic = false
ground2.physicsBody!.affectedByGravity = false
ground2.physicsBody!.categoryBitMask = groundCategory
ground2.physicsBody!.collisionBitMask = groundCategory | heroCategory
self.addChild(ground2)
let ground3 = SKSpriteNode(color: UIColor.blackColor(), size: CGSizeMake(20, 500))
ground3.position = CGPointMake(100, 100)
ground3.physicsBody = SKPhysicsBody(rectangleOfSize: ground3.size)
ground3.physicsBody?.dynamic = false
ground3.physicsBody?.categoryBitMask = invisCategory
ground3.physicsBody!.collisionBitMask = invisCategory | wallCategory
ground3.physicsBody!.contactTestBitMask = wallCategory
self.addChild(ground3)
physicsWorld.contactDelegate = self
scoreLabel.text = "\(score)"
scoreLabel = UILabel(frame: CGRect(x: 10, y: 10, width: 100, height: 20))
scoreLabel.backgroundColor = UIColor(red: 0.6, green: 0.1, blue: 0.1, alpha: 0)
scoreLabel.textColor = UIColor.blackColor()
self.view?.addSubview(scoreLabel)
}
func start() {
isStarted = true
hero.stop()
hero.startRunning()
movingGround.start()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if !isStarted {
start()
score = 0
scoreLabel.text = "0"
wallGenerator.startGeneratingWallsEvery(0.5)
} else {
hero.flip()
}
}
func addScore() {
score++
scoreLabel.text = "\(score)"
}
func didBeginContact(contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.categoryBitMask == invisCategory && secondBody.categoryBitMask == wallCategory || firstBody.categoryBitMask == wallCategory && secondBody.categoryBitMask == invisCategory {
self.addScore()
}
if (firstBody.categoryBitMask & UInt32(heroCategory)) != 0 && (secondBody.categoryBitMask & UInt32(wallCategory)) != 0 {
wallGenerator.removeFromParent()
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let scene = GameOverScene(size: self.size, won: false)
self.view?.presentScene(scene, transition: reveal)
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
Code to CSWall (Wall)
import Foundation
import SpriteKit
class CSWall: SKSpriteNode {
let WALL_WIDTH: CGFloat = 30.0
let WALL_HEIGHT: CGFloat = 50.0
let WALL_COLOR = UIColor.blackColor()
override init() {
super.init(texture: nil, color: WALL_COLOR, size: CGSizeMake(WALL_WIDTH, WALL_HEIGHT))
startMoving()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func startMoving() {
let moveLeft = SKAction.moveByX(-300, y: 0, duration: 1)
runAction(SKAction.repeatActionForever(moveLeft))
}
}
Code that Generates the Wall in game
import SpriteKit
class CSWallGenerator: SKSpriteNode {
var generationTimer: NSTimer?
func startGeneratingWallsEvery(seconds: NSTimeInterval) {
generationTimer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: "generateWall", userInfo: nil, repeats: true)
}
func generateWall() {
var scale: CGFloat
let rand = arc4random_uniform(2)
if rand == 0 {
scale = -1.0
} else {
scale = 1.0
}
let wall = CSWall()
wall.position.x = size.width/2 + wall.size.width/2
wall.position.y = scale * (kCSGroundHeight/2 + wall.size.height/2)
wall.physicsBody = SKPhysicsBody(rectangleOfSize: wall.size)
wall.physicsBody?.dynamic = false
addChild(wall)
}
}

Resources