user6686513
user6686513

Reputation: 11

Swift - How to check to see if sprite is assigned to certain image

Currently, in my code, I have an SKSpriteNode named ball which randomly changes texture when it makes contact with anything. There are 4 different textures/images each with a different colored ball. I want to use an if else statement to check to see if the ball is equal to a specific texture so it can do an action.

I have this code so far, but it does not really check the texture of the ball sprite

func didBeginContact(contact: SKPhysicsContact) {


    if ball.texture == SKTexture(imageNamed: "ball2") && platform3.position.y <= 15 {

        print("Color is matching")

    } else {

        print("Not matching")
    }


}

The if platform3.position.y <= 25 part works, but the ball.texture part of the code does not check to see which texture the ball has.

Upvotes: 0

Views: 476

Answers (2)

Luca Angeletti
Luca Angeletti

Reputation: 59496

ColorType

You can use an enum to represent the possible colors

enum ColorType: String {
    case red = "redBall", green = "greenBall", blue = "blueBall", white = "whileBall"
}

The raw value of each enum case is the name of an image.

Ball

Next declare your sprite class as follow. As you can see I am keeping track of the current colorType. Furthermore as soon as you change colorType, a new texture is assigned to the sprite

class Ball: SKSpriteNode {

    var colorType: ColorType {
        didSet {
            self.texture = SKTexture(imageNamed: colorType.rawValue)
        }
    }

    init(colorType: ColorType) {
        self.colorType = colorType
        let texture = SKTexture(imageNamed: colorType.rawValue)
        super.init(texture: texture, color: .clearColor(), size: texture.size())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Usage

let ball = Ball(colorType: .blue)
if ball.colorType == .blue {
    print("Is blue")
}
ball.colorType = .green

Upvotes: 1

Daniel Tran
Daniel Tran

Reputation: 6171

Set user data when you assign the color to the ball.

ball.userData = ["color": 1]
// later you can check
if (ball.userData["color"] == 1) {

That is the proper way to do. Comparing integer will be faster.

Upvotes: 1

Related Questions