Reputation: 11
(All the following code has been written in Swift Playgrounds)
First I added 3 variables and put those in an array
var rnaBacteriaCopy1 = SKSpriteNode()
var rnaBacteriaCopy2 = SKSpriteNode()
var rnaVirusCopy4 = SKSpriteNode()
let rnaCopies = [
rnaBacteriaCopy1,rnaVirusCopy4,rnaBacteriaCopy2
]
Then I assigned SKTextures to those variables (text is similar for each of them)
rnaBacteriaCopy1 = SKSpriteNode(texture: SKTexture(image:(here I inserted a PNG))
rnaBacteriaCopy1.position = CGPoint(x: 1160, y: 325)
rnaBacteriaCopy1.isHidden = true
addChild(rnaBacteriaCopy1)
Lastly with the public override function touches began
I made it pick a random variable and if the variable picked was a specific one, display the label.
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
var therandomCopy = rnaCopies.randomElement()
rnaCopies.randomElement()?.isHidden = false
if therandomCopy == rnaBacteriaCopy1 {
// Fading Label
var tryAgainLbl = SKLabelNode(text: "Uh oh! Try again.")
tryAgainLbl.fontSize = 70.0
tryAgainLbl.position = CGPoint(x: frame.midX, y: frame.midY)
tryAgainLbl.fontColor = .white
let fadein = SKAction.fadeIn(withDuration: 1)
let remove = SKAction.removeFromParent()
tryAgainLbl.run(SKAction.sequence([fadein,remove]))
addChild(tryAgainLbl)
//Hide this copy
rnaCopies.randomElement()?.isHidden = false
rnaCopies.randomElement()?.isHidden = true
}
At the end I made the random element hide, so you could see other SKTexture and click on it. I already tried making the if statements as specific as possible (putting && != to other variable other than this)
. But it doesn't work, any ideas why?
Upvotes: 1
Views: 61
Reputation: 610
Give the nodes names, this is so you can reference them.
You can set the name where you set the position and isHidden etc..
rnaBacteriaCopy1.name = "bacteria1"
To note, you can give the same name to more than 1 node, so if it makes sense for all of your bacteria nodes to have the name "bacteria", then you can do that.
You can provide the virus a name also:
rnaVirusCopy4.name = "virus"
Now, in your touches began replace this code:
if therandomCopy == rnaBacteriaCopy1 {
With this:
if therandomCopy.name == "bacteria1" {
This means if the randomCopy node has the name "bacteria1" then proceed with the label code inside the if.
Upvotes: 0