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

Sam*_*Sam 8 gamekit sprite-kit game-center-leaderboard swift

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

因此,例如,在GameOverScene意志上他们将被用户认证,并且还能够上传他们的高分.我想我也错过了GameViewController(所有教程逻辑所在的位置)和我制作的众多场景之间的一些差异.

这是我的代码,我尝试使用GKGameCenterControllerDelegateon 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)
    }
Run Code Online (Sandbox Code Playgroud)

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

Flu*_*ity 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
}
Run Code Online (Sandbox Code Playgroud)

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要特别注意

29: let my_leaderboard_id = "YOUR_LEADERBOARD_ID"

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

您还必须添加GameCenter库,并通过iTunes连接实际在弹出窗口中查看您的高分.

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

以下是一些很好的信息:

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

在此输入图像描述


所以你看,SKScene是一个包含Nodes和Actions等所有有趣内容的类,并且是一切(对你很重要)发生的地方.您可以通过编辑器生成这些场景,但是您可能需要创建一个新的.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)
    }
Run Code Online (Sandbox Code Playgroud)

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


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

IOS app解剖:

解剖学

基本上,从右到左,你有一个窗口,它是(如果错误的话,我是错误的)AppDelegate,然后是ViewController,然后是你的View,里面有很多很酷的东西(故事板位于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的学习和冒险:)


Jos*_*rez 5

从我之前编写的Swift 2.2和部分Xcode 7.1起,我仍然可以在游戏中使用“详细答案”。详细的答案,只是跳到底部。为了基本回答您的问题,只要您希望将showLeaderboard()调用到正确的SKScene类中,就可以调用它。

iTunes Connect:

1)登录到您的iTunes Connect帐户。转到我的应用程序,然后选择要与排行榜一起使用的应用程序。

2)转到功能,然后进入游戏中心。单击加号创建排行榜。如果要制作一组排行榜(分组排行榜),请转到右侧,然后单击“更多”。

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

现在在xCode中:

1)通过选择“ +”号来包括GameKit.framework库。

2)将字符串“ GameKit”添加到您的info.plist中

3a)将以下内容与其他导入代码一起添加到GameViewController.swift文件的顶部。

import GameKit
Run Code Online (Sandbox Code Playgroud)

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))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

import GameKit
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

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

6)您必须具有将分数发送到排行榜的功能。在整个类声明之外,我具有以下函数,该函数接受用户的游戏得分作为参数并将其发送到排行榜。它说“ YOUR_LEADERBOARD_ID”的位置,这就是我前面提到的排行榜ID的位置。如此处所示

//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)")
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

8)最后,在游戏结束功能(或您所说的任何功能)中,调用功能“ overrideHighestScore”,以便它可以检查分数是否足以保存。

两者都做完之后,请等待几分钟,直到排行榜连接到您的应用程序(或它们确实已加载)。它适用于我的游戏。希望我没有忘记任何步骤。 用于制作本教程的游戏排行榜的屏幕截图