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
}
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)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With