在特定场景中构建SpriteKit / GameKit排行榜

时间:2016-08-25 15:37:19

标签: swift sprite-kit gamekit game-center-leaderboard

我对Swift很陌生,我在游戏中实现排行榜时遇到了一些麻烦。我刚看了一个教程:'游戏中心排行榜! (Xcode中的Swift 2)'其中GameCenter信息都通过应用程序的一个视图。在我的游戏中,我希望用户能够玩游戏,然后只有当他们在特定的SKScene时,他们才能访问GameCenter。

例如,在GameOverScene上,他们将通过用户身份验证,并且还可以上传他们的高分。我想我也错过了GameViewController(所有教程逻辑所在的位置)和我制作的众多场景之间的一些差异。

以下是我的代码,其中我尝试使用GKGameCenterControllerDelegate上的GameOverScene并创建各种功能以访问GameCenter。当用户在视图中点击某个标签时进行调用:(这显然不起作用,因为我试图访问这样的行上的场景:self.presentViewController(view!, animated:true, completion: nil)

class GameOverScene: SKScene, GKGameCenterControllerDelegate  {

    init(size: CGSize, theScore:Int) {
        score = theScore
        super.init(size: size)
    }
    ...

    override func didMoveToView(view: SKView) {

        authPlayer()

        leaderboardLabel.text = "Tap for Leaderboard"
        leaderboardLabel.fontSize = 12
        leaderboardLabel.fontColor = SKColor.redColor()
        leaderboardLabel.position = CGPoint(x: size.width*0.85, y: size.height*0.1)
        addChild(leaderboardLabel)

        ...

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

        for touch : AnyObject in touches {
            let location = touch.locationInNode(self)

            if(CGRectContainsPoint(leaderBoardLabel.frame, location)){
                saveHighScore(score)
                showLeaderBoard()
            }
        }
    }


    func authPlayer(){

        //Create a play
        let localPlayer = GKLocalPlayer.localPlayer()

        //See if signed in or not
        localPlayer.authenticateHandler = {
            //A view controller and an error handler
            (view,error) in

            //If there is a view to work with
            if view != nil {
                self.presentViewController(view!, animated:true, completion: nil) //we dont want a completion handler
            }

            else{
                print(GKLocalPlayer.localPlayer().authenticated)
            }
        }
    }


    //Call this when ur highscore should be saved
    func saveHighScore(number:Int){

        if(GKLocalPlayer.localPlayer().authenticated){

            let scoreReporter = GKScore(leaderboardIdentifier: "scoreBoard")
            scoreReporter.value = Int64(number)

            let scoreArray: [GKScore] = [scoreReporter]

            GKScore.reportScores(scoreArray, withCompletionHandler: nil)

        }

    }


    func showLeaderBoard(){

        let viewController = self.view.window?.rootViewController
        let gcvc = GKGameCenterViewController()

        gcvc.gameCenterDelegate = self

        viewController?.presentViewController(gcvc, animated: true, completion: nil)


    }


    func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
        gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
    }

关于如何进行此操作的任何建议都会很棒,我认为我可能会让整个场景/视图控制器混乱并导致问题。谢谢!

2 个答案:

答案 0 :(得分:11)

这个答案部分地延续了我们在评论中所停留的位置,因为你没有发布你的整个代码,我无法确切地知道你的挂断在哪里,但这是我和一个单独的指南一起放在一起的(这是你发布的代码的略有不同的版本):

大部分代码的作者:

https://www.reddit.com/r/swift/comments/3q5owv/how_to_add_a_leaderboard_in_spritekit_and_swift_20/

GameViewController.swift:

import UIKit
import SpriteKit
import GameKit

class GameViewController: UIViewController {

    func authenticateLocalPlayer() {
        let localPlayer = GKLocalPlayer.localPlayer()
        localPlayer.authenticateHandler = {(viewController, error) -> Void in

            if (viewController != nil) {
                self.presentViewController(viewController!, animated: true, completion: nil)
            }
            else {
                print((GKLocalPlayer.localPlayer().authenticated))
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        /////authentication//////
        authenticateLocalPlayer()

        //... The rest of the default code
    }

    //... The rest of the default code
}

GameScene.swift(或您想要使用GC的任何场景):

import SpriteKit
import GameKit
import UIKit

// Global scope (I generally put these in a new file called Global.swift)
var score = 0


//sends the highest score to leaderboard
func saveHighscore(gameScore: Int) {
    print ("You have a high score!")
    print("\n Attempting to authenticating with GC...")

    if GKLocalPlayer.localPlayer().authenticated {
        print("\n Success! Sending highscore of \(score) to leaderboard")

        //---------PUT YOUR ID HERE:
        //                          |
        //                          |
        //                          V
        let my_leaderboard_id = "YOUR_LEADERBOARD_ID"
        let scoreReporter = GKScore(leaderboardIdentifier: my_leaderboard_id)

        scoreReporter.value = Int64(gameScore)
        let scoreArray: [GKScore] = [scoreReporter]

        GKScore.reportScores(scoreArray, withCompletionHandler: {error -> Void in
            if error != nil {
                print("An error has occured:")
                print("\n \(error) \n")
            }
        })
    }
}

// Your scene:
class GameScene: SKScene, GKGameCenterControllerDelegate {

    // Local scope variables (for this scene):

    // Declare a new node, then initialize it
    let call_gc_node   = SKLabelNode(fontNamed:"Chalkduster")
    let add_score_node = SKLabelNode(fontNamed: "Helvetica")


    override func didMoveToView(view: SKView) {

        // Give our GameCenter node some stuff
        initGCNode: do {

            // Set the name of the node (we will reference this later)
            call_gc_node.name = "callGC"

            // Default inits
            call_gc_node.text = "Send your HighScore of \(score) into Game Center"
            call_gc_node.fontSize = 25
            call_gc_node.position = CGPoint(
                x:CGRectGetMidX(self.frame),
                y:CGRectGetMidY(self.frame))

            // Self here is the instance (object) of our class, GameScene
            // This adds it to our view
            self.addChild(call_gc_node)
        }

        // Give our Add label some stuff
        initADDLabel: do {

            // Set the name of the node (we will reference this later)
            add_score_node.name = "addGC"

            // Basic inits
            add_score_node.text = "ADD TO SCORE!"
            add_score_node.fontSize = 25
            add_score_node.position = call_gc_node.position

            // Align our label some
            add_score_node.runAction(SKAction.moveByX(0, y: 50, duration: 0.01))

            // Add it to the view
            self.addChild(add_score_node)
        }

    }


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

            // Get the position of our click
            let TPOINT = touch.locationInNode(self)

            // Get the name (string) of the node that was touched
            let
                node_that_was_touched: String?
                                                = nodeAtPoint(TPOINT).name


            // Prepare for switch statement, when we unwrap the optional, we don't want nil
            guard (node_that_was_touched != nil)
                else { print("-> before switch: found nil--not entering Switch");
                    return
            }


            // Find out which node we clicked based on node.name?, then do stuff:
            switch node_that_was_touched! {

                case "callGC":
                    // We clicked the GC label:

                    GameOver: do {

                        print("GAME OVER!")

                        // If we have a high-score, send it to leaderboard:
                        overrideHighestScore(score)

                        // Reset our score (for the next playthrough)
                        score = 0

                        // Show us our stuff!
                        showLeader()
                    }

                case "addGC":
                    // we clicked the Add label:

                    // Update our *current score*
                    score += 1


                default: print("no matches found")
            }

        }

    }


    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
        call_gc_node.text = "Send your HighScore of \(score) into Game Center"

    }


    // Gamecenter
    func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
        gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
    }

    //shows leaderboard screen
    func showLeader() {
        let viewControllerVar = self.view?.window?.rootViewController
        let gKGCViewController = GKGameCenterViewController()
        gKGCViewController.gameCenterDelegate = self
        viewControllerVar?.presentViewController(gKGCViewController, animated: true, completion: nil)
    }

    // Your "game over" function call
    func overrideHighestScore(gameScore: Int) {
        NSUserDefaults.standardUserDefaults().integerForKey("highscore")
        if gameScore > NSUserDefaults.standardUserDefaults().integerForKey("highscore")
        {
            NSUserDefaults.standardUserDefaults().setInteger(gameScore, forKey: "highscore")
            NSUserDefaults.standardUserDefaults().synchronize()

            saveHighscore(gameScore)
        }
    }
}

特别注意

  

29:let my_leaderboard_id = "YOUR_LEADERBOARD_ID"

我在那里放了一些愚蠢的ASCII艺术,以确保你不会错过它。您必须从GameCenter设置中输入您的实际排行榜ID。

您还必须添加GameCenter库,并进行iTunes连接以在弹出窗口中实际看到您的高分。

我认为你最初的问题是没有理解SpriteKit甚至iOS视图如何工作的后端(这完全没问题,因为Apple让人很容易进入并且很容易)。但是,如您所见,由于您的实施方式会有所不同,因此遵循指南/教程可能会很困难。

以下是一些很好的信息:

SK中每个帧发生的情况图:

enter image description here

所以你看,SKScene是一个包含节点和动作等所有有趣内容的类,并且是一切(对你很重要)发生的地方。您可以通过编辑器生成这些场景,但是您可能需要创建一个新的.swift文件(因为每个场景都有自己的逻辑)。

编辑器只是初始化一堆东西的“捷径”,老实说,你可以用很少的代码制作完整的游戏(但你很快发现你想要更多

所以在这段代码中,你声明了GameScene或PauseScreen(它们基本上只是类声明,继承自SKScene),你很快就会发现这一行谈论ISNT是一个场景:

  

override func didMoveToView(view: SKView)   ..它正在调用SKView ......那是什么,它来自哪里?

     

(在这里阅读SKView,看看它的继承):

     

https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKView/index.html#//apple_ref/occ/cl/SKView

我们在GameViewController文件中找到这个SKView声明(这只是一个类),注意它与普通的iOS应用程序大致相同,因为它继承了UIViewController:

override func viewDidLoad() {
    super.viewDidLoad()
    if let scene = GameScene(fileNamed:"GameScene") {
        // Configure the view.
        let skView = self.view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true

        /* Sprite Kit applies additional optimizations to improve               rendering performance */
        skView.ignoresSiblingOrder = true

        /* Set the scale mode to scale to fit the window */
        scene.scaleMode = .AspectFill

        skView.presentScene(scene)
    }

同样,该方法在GameViewController.swift中声明,基本上就是这样: class GameViewController: UIViewController

那么所有这些与iOS应用和SpriteKit有什么关系?好吧,他们都被捣碎在彼此之上:

IOS app解剖:

anatomy

基本上,从右到左,你有一个Window,它是(如果错误的话,我是错误的)AppDelegate,然后是ViewController,然后你的View,里面有所有很酷的东西(Storyboards位于View里面)就像SKScenes坐在View ....标签,节点或按钮内部一样,都位于各自的类中((视图)))

这都是继承的重要组成部分。

查看Apple网站了解更多信息。

https://developer.apple.com/library/safari/documentation/UserExperience/Conceptual/MobileHIG/ContentViews.html#//apple_ref/doc/uid/TP40006556-CH13-SW1

https://developer.apple.com/spritekit/

https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SpriteKitFramework_Ref/

https://developer.apple.com/library/safari/documentation/UserExperience/Conceptual/MobileHIG/Anatomy.html

基本上,一切都是继承自类继承的类的类,依此类推......它可能会变得混乱。你也可以通过CMD +点击它们在Xcode中看到这些遗产,这会将你跳转到源文件。

Goodluck与你在SpriteKit的学习和冒险:)

答案 1 :(得分:4)

详细解答仍然适用于我的游戏,如Swift 2.2和部分Xcode 7.1,我刚才写过。详细的答案,但只是跳到底部。要基本回答你的问题,只要你想调用它就会调用showLeaderboard(),只需将特定函数放在正确的SKScene类中。

iTunes Connect:

1)登录iTunes Connect account。转到我的应用程序,然后选择您想要排行榜的应用程序。

2)Go to Features, and then Game Center。单击加号以创建排行榜。如果您想制作一组排行榜(分组排行榜,请转到右侧并点击“更多”。

3)点击加号后,按照所需的排行榜说明进行操作。如果你不确定的话,首先要做一个排行榜。分配给它的“Leaderboard ID”将在访问时在代码中用作字符串,因此请确保输入一些不错的内容。

现在在xCode中:

1)Include the GameKit.framework library by choosing the "+" sign.

2)Add the string "GameKit" into your info.plist

3a)使用其他导入代码在GameViewController.swift文件的顶部添加以下内容。

import GameKit

3b)在同一个swift文件中的类中添加以下函数。

    func authenticateLocalPlayer() {
    let localPlayer = GKLocalPlayer.localPlayer()
    localPlayer.authenticateHandler = {(viewController, error) -> Void in

        if (viewController != nil) {
            self.presentViewController(viewController!, animated: true, completion: nil)
        }
        else {
            print((GKLocalPlayer.localPlayer().authenticated))
        }
    }
}

4)从viewDidLoad()函数内部调用“authenticateLocalPlayer”函数。

5a)现在,转到GameScene.swift文件(或执行的任何地方)。并在顶部添加以下内容。

import GameKit

5b)在类函数中添加以下代码。

//shows leaderboard screen
func showLeader() {
    let viewControllerVar = self.view?.window?.rootViewController
    let gKGCViewController = GKGameCenterViewController()
    gKGCViewController.gameCenterDelegate = self
    viewControllerVar?.presentViewController(gKGCViewController, animated: true, completion: nil)
}
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
    gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}

在我的游戏中,我有一个按钮来显示排行榜,所以只要调用“showLeader”功能来显示排行榜。

6)您必须具有将分数发送到排行榜的功能。在整个类声明之外,我有以下函数接受用户的游戏分数作为参数并将其发送到排行榜。如果它显示“YOUR_LEADERBOARD_ID”,那么我前面提到的排行榜ID就在这里。As pictured here

//sends the highest score to leaderboard
func saveHighscore(gameScore: Int) {

    print("Player has been authenticated.")

    if GKLocalPlayer.localPlayer().authenticated {

        let scoreReporter = GKScore(leaderboardIdentifier: "YOUR_LEADERBOARD_ID")
        scoreReporter.value = Int64(gameScore)
        let scoreArray: [GKScore] = [scoreReporter]

        GKScore.reportScores(scoreArray, withCompletionHandler: {error -> Void in
            if error != nil {
                print("An error has occured: \(error)")
            }
        })
    }
}

7)这是我在游戏结束时调用的功能。它决定分数是否大于之前的最高分,如果是,则将其发送到排行榜。 此代码完全取决于您,但请确保它调用saveHighscore函数,该函数将数据发送到排行榜。

func overrideHighestScore(gameScore: Int) {
    NSUserDefaults.standardUserDefaults().integerForKey("highscore")
    if gameScore > NSUserDefaults.standardUserDefaults().integerForKey("highscore") {

        NSUserDefaults.standardUserDefaults().setInteger(gameScore, forKey: "highscore")
        NSUserDefaults.standardUserDefaults().synchronize()

        saveHighscore(gameScore)
    }
}

注意最后调用函数“saveHighscore”。

8)最后,在游戏过功能(或任何你称之为)中,调用函数“overrideHighestScore”,以便检查分数是否足以保存。

执行这两项操作后,请等待几分钟,直到排行榜连接到您的应用(或他们确实加载)。它适用于我的游戏。 希望我没有忘记用于制作本教程的任何步骤。 Screenshot of my game leaderboards