This task builds a very simple game, whereby the player has to move a label to the appropriately coloured box.
class
add the following code:
let label = SKLabelNode()
let blueBin = SKSpriteNode()
let yellowBin = SKSpriteNode()
func setupDragLabel(){
//set the font and position of the label
label.fontName = "Chalkduster";
label.fontSize = 20
label.position = CGPoint(x: frame.midX, y: frame.midY+100)
//get a random Bool
let blue = Bool.random() //for <Swift 4.2 use arc4random_uniform(2) == 0
//depending on the random number set the text and name to either Blue or Yellow
if blue
{
label.text = "blue"
label.name = "blue"
}else{
label.text = "yellow"
label.name = "yellow"
}
//add the label to the scene
addChild(label)
}
didMove(to view:)
method and replace it with the function call below:
setupDragLabel()
touchesBegan(touches: event:)
method as we will only need to consider touches that have moved or endedfunc setupTargets(){
//setup the yellow bin with colour, dimensions and add to scene
yellowBin.color = SKColor.yellow
yellowBin.size = CGSize(width: 200, height: 200)
yellowBin.position = CGPoint(x: 200, y: 200)
addChild(yellowBin)
//note that we can determine property of a fixed type using shorthand, shown here for setting colour
blueBin.color = .blueColor();
blueBin.size = CGSize(width: 200, height: 200)
blueBin.position = CGPoint(x: 440, y:200)
addChild(blueBin)
}
Then call this method by adding the following line inside the didMoveToView
method:
setupTargets()
Run the game to ensure you can see the label and two drop zones.
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
//get a touch
let touch = touches.first!
//if it started in the label, move it to the new location
if label.frame.contains(touch.previousLocation(in: self)){
label.position = touch.location(in: self)
}
}
It is worth being aware that because iOS devices can detect multiple touches, we have to pick one to use. That is what the touches.anyObject()
function call of the code does.
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
//if label is called yellow and its centre is inside the yellow target
if label.name == "yellow"{
if yellowBin.frame.contains(label.position){
//remove it and create a new label
label.removeFromParent()
setupDragLabel()
}
}
//same process for blue label
if label.name == "blue"{
if blueBin.frame.contains(label.position){
//remove it and create a new label
label.removeFromParent()
setupDragLabel()
}
}
}
touchesEnded
method. Refactor the code to avoid repetition where possible - this will require the creation of new functions.Use what you have learned to develop a game based on similar principles, for example a jigsaw.