How to animate GMSMarker? - ios

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()
}
}

Related

How to compare two colours variable have same color [duplicate]

I want change button background for different state.
I try so:
#IBAction func addToShedulerAction(sender: UIButton) {
println(sender.backgroundColor)
if sender.backgroundColor==UIColor.redColor(){
sender.backgroundColor==UIColor.whiteColor()
}
else //if sender.backgroundColor==UIColor.whiteColor()
{
sender.backgroundColor=UIColor.redColor()
}
}
but in first push button println print nil and background change to red, in second push println print "Optional(UIDeviceRGBColorSpace 1 0 0 1)" and color doesn't change
Previous answers are wrong
cause
UIColor.black.isEqual(UIColor(red: 0, green: 0, blue: 0, alpha: 1))
returns false
add this code to your project (Swift 4)
extension UIColor {
static func == (l: UIColor, r: UIColor) -> Bool {
var r1: CGFloat = 0
var g1: CGFloat = 0
var b1: CGFloat = 0
var a1: CGFloat = 0
l.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
var r2: CGFloat = 0
var g2: CGFloat = 0
var b2: CGFloat = 0
var a2: CGFloat = 0
r.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
return r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2
}
}
func == (l: UIColor?, r: UIColor?) -> Bool {
let l = l ?? .clear
let r = r ?? .clear
return l == r
}
so now
UIColor.black == UIColor(red: 0, green: 0, blue: 0, alpha: 1)
returns true
and for you:
if sender.backgroundColor == .red {
sender.backgroundColor = .white
} else {
sender.backgroundColor = .red
}
now your code looks pretty :)
You don't compare colors using the == operator. You do it like this and you need the ! to unwrap the optional color:
if sender.backgroundColor!.isEqual(UIColor.redColor()) {
            
}
Also, remove the extraneous = in your assignment statement. It should be:
sender.backgroundColor = UIColor.whiteColor()
Remember when you are comparing UIColors you have to write description at the end of the color for both side, if you don't write this, every time it will enter into else block. For Example, see the below code
if(ocularPlus1Btn.backgroundColor?.description == UIColor.init(red: 23.0 / 255.0, green: 82 / 255.0, blue: 84 / 255.0, alpha: 1).description) {
return "positive"
} else {
return "negative"
}
You have a mistake in your first if clause. It should be:
if sender.backgroundColor.isEqual(UIColor.redColor()){
sender.backgroundColor=UIColor.whiteColor // only one '=' here
}

Why can't the method be called?

I just cloned a project from GitHub, and I added the relevant folder to my project. When I run my project, the animation effect can be displayed normally, but the images on the animation can't be displayed. I have tried re-cloning the complete code, but it still does the same. I'm sure that all the codes and images are completely cloned.
I added a breakpoint, realizing that the func circleMenu is never called.
Can someone please explain this, or at least tell me what I need to write to get it correct?
Here is my code:
import UIKit
import CircleMenu
extension UIColor {
static func color(_ red: Int, green: Int, blue: Int, alpha: Float) -> UIColor {
return UIColor(
red: 1.0 / 255.0 * CGFloat(red),
green: 1.0 / 255.0 * CGFloat(green),
blue: 1.0 / 255.0 * CGFloat(blue),
alpha: CGFloat(alpha))
}
}
class FirstViewController: UIViewController, CircleMenuDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
#IBAction func to2(_ sender: UIButton) {
let sb = UIStoryboard(name:"Main",bundle: Bundle.main)
let view2 = sb.instantiateViewController(withIdentifier: "view2")
layerTransition(animTye: .cube, subType: .ramdom, curve: .EaseInEaseOut, duration: 0.4, layer: (self.view.window?.layer)!)
self.present(view2,animated: true,completion: nil)
}
// let secondView = ViewController()
#IBAction func toView2(_ sender: UIButton) {
let sb = UIStoryboard(name:"Main",bundle: Bundle.main)
let secondViewController = sb.instantiateViewController(withIdentifier: "SecondViewController")
layerTransition(animTye: .cube, subType: .ramdom, curve: .EaseInEaseOut, duration: 0.4, layer: (self.view.window?.layer)!)
self.present(secondViewController,animated: true,completion: nil)
}
var imagePickerController:UIImagePickerController!
enum TransitionAnimType : Int {
case fade = 0,
push,
reveal,
moveIn,
cube,
suckEffect,
oglFlip,
rippleEffect,
pageCurl,
pageUnCurl,
cameraIrisHollowOpen,
cameraIrisHollowClose,
curlDown,
curlUp,
flipFromLeft,
flipFromRight,
ramdom
}
enum TransitionSubType : Int {
case top = 0,
left,
bottom,
right,
ramdom
}
enum TransitionCurve : Int {
case Default = 0,
EaseIn,
EaseOut,
EaseInEaseOut,
Linear,
Ramdom
}
private func animationType(animType: TransitionAnimType) -> String {
let animTypeArray = ["fade", "push", "reveal", "moveIn", "cube", "suckEffect", "oglFlip", "rippleEffect", "pageCurl", "pageUnCurl", "cameraIrisHollowOpen", "cameraIrisHollowClose", "curlDown", "curlUp", "flipFromLeft", "flipFromRight", "ramdom"]
return objectFromDataSource(array: animTypeArray, index: animType.rawValue, isRamdom: (TransitionAnimType.ramdom == animType)) as! String
}
private func animationSubType(subType: TransitionSubType) -> String {
let animSubTypeArray = [CATransitionSubtype.fromTop, CATransitionSubtype.fromLeft, CATransitionSubtype.fromBottom, CATransitionSubtype.fromRight]
return objectFromDataSource(array: animSubTypeArray, index: subType.rawValue, isRamdom: (TransitionSubType.ramdom == subType)) as! String
}
private func animationCurve(curve: TransitionCurve) -> String {
let animCurveArray = [CAMediaTimingFunctionName.default, CAMediaTimingFunctionName.easeIn, CAMediaTimingFunctionName.easeOut, CAMediaTimingFunctionName.easeInEaseOut, CAMediaTimingFunctionName.linear]
return objectFromDataSource(array: animCurveArray, index: curve.rawValue, isRamdom: (TransitionCurve.Ramdom == curve)) as! String
}
private func objectFromDataSource(array: Array<Any>, index: Int, isRamdom: Bool) -> AnyObject {
let count = array.count
let i = isRamdom ? Int(arc4random_uniform(UInt32(count))) : index
return array[i] as AnyObject
}
func layerTransition(animTye: TransitionAnimType, subType: TransitionSubType, curve: TransitionCurve, duration: CGFloat, layer: CALayer) {
let key = "transition"
if layer.animation(forKey: key) != nil {
layer.removeAnimation(forKey: key)
}
let transition = CATransition()
transition.duration = CFTimeInterval(duration)
transition.type = CATransitionType(rawValue: animationType(animType: animTye))
transition.subtype = CATransitionSubtype(rawValue: animationSubType(subType: subType))
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName(rawValue: animationCurve(curve: curve)))
transition.isRemovedOnCompletion = true
layer.add(transition, forKey: key)
}
// let colors = [UIColor.redColor(), UIColor.grayColor(), UIColor.greenColor(), UIColor.purpleColor()]
let items: [(icon: String, color: UIColor)] = [
("icon_home", UIColor(red: 0.19, green: 0.57, blue: 1, alpha: 1)),
("icon_search", UIColor(red: 0.22, green: 0.74, blue: 0, alpha: 1)),
("notifications-btn", UIColor(red: 0.96, green: 0.23, blue: 0.21, alpha: 1)),
("settings-btn", UIColor(red: 0.51, green: 0.15, blue: 1, alpha: 1)),
("nearby-btn", UIColor(red: 1, green: 0.39, blue: 0, alpha: 1))
]
// #IBInspectable var buttonsCount: Int = 3
// #IBInspectable var duration: Double = 2 // circle animation duration
// #IBInspectable var distance: Float = 100 // distance between center button and buttons
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
}
// MARK: <CircleMenuDelegate>
func circleMenu(_: CircleMenu, willDisplay button: UIButton, atIndex: Int) {
button.backgroundColor = items[atIndex].color
button.setImage(UIImage(named: items[atIndex].icon), for: .normal)
let image = UIImage(named:items[atIndex].icon)
// set highlited image
let highlightedImage = UIImage(named: items[atIndex].icon)?.withRenderingMode(.alwaysTemplate)
button.setImage(highlightedImage, for: .highlighted)
button.tintColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
}
func circleMenu(_: CircleMenu, buttonWillSelected _: UIButton, atIndex: Int) {
print("button will selected: \(atIndex)")
}
func circleMenu(_: CircleMenu, buttonDidSelected _: UIButton, atIndex: Int) {
// let sb = UIStoryboard(name:"Main",bundle: Bundle.main)
// let secondView = sb.instantiateViewController(withIdentifier: "secondView")
print("button did selected: \(atIndex)")
if(atIndex == 0)
{
if(UIImagePickerController.isSourceTypeAvailable(.camera))
{
self.imagePickerController = UIImagePickerController()
self.imagePickerController.delegate = self
self.imagePickerController.allowsEditing = true
self.imagePickerController.sourceType = UIImagePickerController.SourceType.camera
layerTransition(animTye: .cameraIrisHollowOpen, subType: .ramdom, curve: .EaseInEaseOut, duration: 0.4, layer: (self.view.window?.layer)!)
self.present(self.imagePickerController,animated: true,completion: nil)
}
}
}
}
At this moment you only declare your delegate. Make sure you also set the delegate otherwise your delegate methodes wouldn't be called.

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 collect "diamonds", add "diamonds" to "diamonds?

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!

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)
}

Resources