Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create movement buttons left/right?

Please help. I am a beginner on Swift. I've added sprites for player and left/right buttons. But how can I add an action for every button and apply these actions to the player?

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

    var player: SKSpriteNode!
    var leftMove: SKSpriteNode!
    var rightMove: SKSpriteNode!

    override func didMoveToView(view: SKView) {

        player = SKSpriteNode (imageNamed: "player")

        player.position = CGPoint(x:127, y:125)

        addChild(player)


        leftMove = SKSpriteNode (imageNamed: "leftMove")

        leftMove.position = CGPoint(x:80, y:35)

        leftMove.size = CGSize (width: 55, height: 55)

        addChild(leftMove)


        rightMove = SKSpriteNode (imageNamed: "rightMove")

        rightMove.position = CGPoint(x:160, y:35)

        rightMove.size = CGSize (width: 55, height: 55)

        addChild(rightMove)

        physicsWorld.contactDelegate = self


    }
like image 869
Metman Avatar asked Jan 26 '16 22:01

Metman


1 Answers

Give the buttons a unique name like:

leftMove.name = "Left"
rightMove.name = "Right"

Implement the logic in touchesBegan:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

  /* Called when a touch begins */
  for touch: AnyObject in touches {
    let location = touch.locationInNode(self)
    let node = self.nodeAtPoint(location)

    if (node.name == "Left") {
        // Implement your logic for left button touch here:
        player.position = CGPoint(x:player.position.x-1, y:player.position.y)
    } else if (node.name == "Right") {
        // Implement your logic for right button touch here:
        player.position = CGPoint(x:player.position.x+1, y:player.position.y)
    }
  }
}
like image 149
Stefan Avatar answered Oct 13 '22 13:10

Stefan