Thursday, September 10, 2015

Quick Tip: How to use the remote control in your TVOS Apps for Apple TV in SWIFT

How to use the remote control in your tvOS Apps for Apple TV in SWIFT

There are already dozens of 'Hello world' tutorials published for the new Apple tvOS, so let's do something different. I'll show how to use the remote control to move a sprite on Apple TV. It was surprisingly easy and took me only 10 minutes to implement:

1. Download the XCode 7.1 Beta from the Apple Developer Portal:

2. Create a new project:

3. Open 'GameScene.swift':

4. Replace the complete code with this snippet:

import SpriteKit

class GameScene: SKScene {
    let sprite = SKSpriteNode(imageNamed:"Spaceship")
    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
        // Add Sprite
        sprite.xScale = 0.5
        sprite.yScale = 0.5
        sprite.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
        // Register Swipe Events
        let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedRight:"))
        swipeRight.direction = .Right
        let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedLeft:"))
        swipeLeft.direction = .Left
        let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedUp:"))
        swipeUp.direction = .Up
        let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedDown:"))
        swipeDown.direction = .Down
    // Handle Swipe Events
    func swipedRight(sender:UISwipeGestureRecognizer){
        sprite.position = CGPoint(x: sprite.position.x + 10, y: sprite.position.y)
    func swipedLeft(sender:UISwipeGestureRecognizer){
        sprite.position = CGPoint(x: sprite.position.x - 10, y: sprite.position.y)
    func swipedUp(sender:UISwipeGestureRecognizer){
        sprite.position = CGPoint(x: sprite.position.x, y: sprite.position.y+10)
    func swipedDown(sender:UISwipeGestureRecognizer){
        sprite.position = CGPoint(x: sprite.position.x, y: sprite.position.y-10)
    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */


5. Start the Simulator:

6. Show the remote control:

7. Move the sprite around: 

This was the most confusing part and costs me some minutes. You have to press the option key (alt) on you Mac keyboard and move the mouse around on the touch area of the remote control window. No mouse clicks!!!

That's all for today.


1 comment:

  1. hi,
    thank you for the code
    but what do i have to do in order to keep moving the sprite?
    i want to create a drag and drop game