Swift - Missing argument for parameter "coder" in call - ios

Im am trying to pause or stop an SKAction that is being repeated forever which should happen when the user presses the pause button. I have found a way to stop the music but i cant call the function it is in because of this error. It says exactly: Missing argument for parameter 'coder' in call.
Class GameViewController: UIViewController, SwiftrisDelegate, UIGestureRecognizerDelegate {
#IBAction func didPause(sender: UIButton) {
if self.scene.paused == false{
self.scene.stopTicking()
self.scene.paused = true
GameScene().stopGameMusic() //error on this line
}
}
}
class GameScene: SKScene {
runAction(SKAction.playSoundFileNamed("theme.mp3", waitForCompletion: true), withKey:("themeSong"))
func stopGameMusic() {
removeActionForKey("themeSong")
}
}

There is no initializer for GameScene that takes no arguments - you haven't defined one nor is one inherited from SKScene. If you intend to create a GameScene each time 'pause' is pushed, which is a questionable approach in itself, then you'll need to call an existing initializer or to create an initializer w/o any arguments.
It looks like the designated initializer for SKScene is init(size: CGSize). So instead of simply calling GameScene() call GameScene(size: ...) or, in the class GameScene define
class GameScene : SKScene {
// ...
init () {
super.init (size: ...)
}
}

Related

What's the cleanest way to call a method from one SKScene to another in Swift?

So I got in my game 3 different scenes: MenuScene, GameScene and GameOverScene.
I would like to know how I can get the score variable located in GameScene from GameOverScene so I can show it up there after the player loses.
So in GameScene, I created this simple getter:
func getScore() -> Int {
return self.score
}
But if I try to do GameScene.getScore() from a different Scene I get an error.
Tried using "class" before func
class func getScore() -> Int {
return self.score
}
But that also gives me an error from GameScene saying:
"Instance member 'score' cannot be used on type GameScene"
So how's the best way to do it? I don't want to create a global variable for this, it would be ugly.
This is quite easy actually. When you segue to the new scene, you can also pass in a variable with it... Here is an example.
GameOverScene.swift
var score:Int = 0
GameScene.swift
var score:Int = THE USERS SCORE
func segue(){
let gameScene = GameOverScene(size: self.size)
gameScene.score = score
let transition = SKTransition.doorsCloseHorizontalWithDuration(0.5)
gameScene.scaleMode = SKSceneScaleMode.AspectFill
self.scene!.view?.presentScene(gameScene, transition: transition)
}
You need to keep an instance of GameScene in your MenuScene class (recommended). Alternatively, you can store the score in a global storage medium.
To enter the game scene, you need to create it first, right?
let scene = SKScene(fileNamed: "blah blah blah")
view.presentScene(scene)
Now instead of creating the scene and assigning it to a local variable, you assign it to a class level variable.
var gameScene: GameScene?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if (...) {
gameScene = SKScene(fileNamed: "blah blah blah")
view.presentScene(gameScene!)
}
}
Then, when appropriate, you can access the score like this:
gameScene.getScore()
Another way is to use NSUserDefaults, but you don't seem to like it.
The final way that I can think of is to use static variables. You put all the stuff that you need to pass between the two scenes in a class as static variables. The disadvantage of this is that unless you declare the class private and put both scenes and the class in the same file, others classes can access and change the variables. This reduces maintainability.
Explicit getters are not needed in Swift, btw.
There are many ways to achieve what do you want to do. You could use a manager class , a shared instance to maintain your game variables.
Why this choice?
Because you will want to save your values or your profile or you will want to reset all the game progress, because you will want to select the old 2nd level when you have unlocked the 18th level, or repeat a failed level without accumulating values. It's fast to do it and you can handle separately your common game variables (it seems that I'm selling pots in an advertisement..)
class Settings: NSObject { // NSCoding in case you want to save your data
var score: Int = 0
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeInteger(score, forKey: "score")
}
init(coder aDecoder: NSCoder!) {
score = aDecoder. decodeIntegerForKey("score")
}
override init() {
super.init()
// do whatever you want to initializing your settings
}
}
class GameManager: NSObject {
static let sharedInstance = GameManager()
var settings : Settings! = Settings()
}
class MenuScene: SKScene {
let gameManager = GameManager.sharedInstance
override func didMoveToView(view: SKView) {
print("the current score is \(self.gameManager.settings.score)")
}
}
class GameScene: SKScene {
let gameManager = GameManager.sharedInstance
override func didMoveToView(view: SKView) {
print("the current score is \(self.gameManager.settings.score)")
}
}
class GameOverScene: SKScene {
let gameManager = GameManager.sharedInstance
override func didMoveToView(view: SKView) {
print("the current score is \(self.gameManager.settings.score)")
}
}

Use a boolean value from another scene in SpriteKit - Swift

I am trying to use a variable from my GameScene.swift file on my GameViewController.swift file to time my interstitial ads appropriately. It's a boolean value that determines if my player is dead or not.
var died = Bool()
That's all I did to create the variable in my GameScene.
When died == true in my GameScene, I want to send that to my GameViewController and then show an interstitial ad. I really just need to know how to pass a boolean between scenes. Thanks in advanced for your help.
You can follow these steps.
Do this in your GameScene:
protocol PlayerDeadDelegate {
func didPlayerDeath(player:SKSpriteNode)
}
class GameScene: SKScene {
var playerDeadDelegate:PlayerDeadDelegate?
...
// during your game flow the player dead and you do:
playerDeadDelegate.didPlayerDeath(player)
...
}
In the GameViewController you do:
class GameViewController: UIViewController,PlayerDeadDelegate {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
...
scene.playerDeadDelegate = self
}
}
func didPlayerDeath(player:SKSpriteNode) {
print("GameViewController: the player is dead now!!!")
// do whatever you want with the property player..
}
}
Your GameScene should have a reference object as delegate (e.g conforms to GameSceneDelegate protocol) which is actually pointing to GameViewController object. Then when died becomes true, inform your delegate object (GameViewController object) about this event via a delegate-method and implement that method by conforming to the above protocol in your GameViewController class.

SpriteKit: run action while scene is paused

I have a button to pause the game on my code. What I want is that pausing the game with that button makes a message that says "Paused" to appear. However, since the scene is paused, the message does not appear.
What I have right now is a SKLabelNode with the alpha on 0.0 at the beginning and when the user pauses the game, it changes to 1.0 with fadeInWithDuration(). Then when the user presses the button again, it changes back to 0.0 with fadeOutWithDuration(). The problem is that the SKAction with fadeInWithDuration() does not run when the scene is paused.
How could I achieve this?
The best way, one Apple also uses in "DemoBots", is to create a world node that you pause instead of the scene.
Create a worldNode property
class GameScene: SKScene {
let worldNode = SKNode()
}
add it to the scene in didMoveToView
addChild(worldNode)
and than add everything you need paused to the worldNode. This includes actions that are normally run by the scene (eg. timers, enemy spawning etc)
worldNode.addChild(someNode)
worldNode.run(someSKAction)
Than in your pause func you say
worldNode.isPaused = true
physicsWorld.speed = 0
and in resume
worldNode.isPaused = false
physicsWorld.speed = 1
You can also add an extra check in your Update function if you have stuff there that you want to ignore when paused.
override func update(_ currentTime: CFTimeInterval) {
guard !worldNode.isPaused else { return }
// your code
}
This way it's much easier to add your paused label or other UI when your game is paused because you haven't actually paused the scene. You can also run any action you want, unless that action is added to the worldNode or to a child of worldNode.
Hope this helps
Instead of pausing the scene, you could layer some nodes your scene like this
SKScene
|--SKNode 1
| |-- ... <--place all scene contents here
|--SKNode 2
| |-- ... <--place all overlay contents here
Then when you want to pause the game, you pause only SKNode 1.
This allows node SKNode 2 to continue to run, so you can do things like have animations going, and have a button that unpauses the scene for you, without having the need to add some non Sprite Kit object into the mix.
A quick workaround would be to pause your game after the SKLabelNode appears on screen:
let action = SKAction.fadeOutWithDuration(duration)
runAction(action) {
// Pause your game
}
Another option would be to mix UIKit and SpriteKit and inform the ViewController back that it needs show this label.
class ViewController: UIViewController {
var gameScene: GameScene!
override func viewDidLoad() {
super.viewDidLoad()
gameScene = GameScene(...)
gameScene.sceneDelegate = self
}
}
extension ViewController: GameSceneDelegate {
func gameWasPaused() {
// Show your Label on top of your GameScene
}
}
protocol GameSceneDelegate: class {
func gameWasPaused()
}
class GameScene: SKScene {
weak var sceneDelegate: GameSceneDelegate?
func pauseGame() {
// Pause
// ...
sceneDelegate?.gameWasPaused()
}
}
So you want to pause the game AFTER the action execution has completed.
class GameScene: SKScene {
let pauseLabel = SKLabelNode(text: "Paused")
override func didMoveToView(view: SKView) {
pauseLabel.alpha = 0
pauseLabel.position = CGPoint(x: CGRectGetMaxY(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(pauseLabel)
}
func pause(on: Bool) {
switch on {
case true: pauseLabel.runAction(SKAction.fadeInWithDuration(1)) {
self.paused = true
}
case false:
self.paused = false
pauseLabel.runAction(SKAction.fadeOutWithDuration(1))
}
}
}
I would add the label with
self.addChild(nameOfLabel)
and then pause the game with
self.scene?.paused = true
This should all go in the if pauseButton is touched portion of your code.

Assigning another variable from a different class in an #IBAction?

In my GameScene.swift file, I have the following member variable "chosenBall" that I want to assign in another file called ChooseBall.swift.
class GameScene: SKScene, SKPhysicsContactDelegate {
internal var chosenBall: BallType!
}
My ChooseBall.swift file looks like this.
class ChooseBall: UIViewController {
#IBAction func chooseBeachBall(sender: UIButton) {
chosenBall = BallType.BeachBall
}
}
I am getting a compiler error saying:
Use of unresolved identifier 'chosenBall'
How can I fix it ?
I haven't used SpriteKit so I do not know the basics on where and when to instantiate Scenes.
However, the error you are getting is because you have not created an instance of GameScene and made that accessible from your view controller.
A possible solution could be the following code, but again, I'm not sure when or where the scene should be instantiated.
class ChooseBall: UIViewController {
var scene = GameScene()
#IBAction func chooseBeachBall(sender: UIButton) {
scene.chosenBall = BallType.BeachBall
}
}

Swift Delegate Not Being Called

I have a view with a delegate that I want to have call numpadView(numpadView:) in GameController upon button press, however I can't get it to work. The overload of touchesBegan() works fine, it's really the line with pressDelegate?.numpadView(self) which doesn't call the delegate function in the GameController class. I'm stumped as to what's missing to get it to work?
I cleaned the code to leave only the essential related to the problem for simplicity.
NumpadView.swift
protocol NumpadPressDelegateProtocol {
func numpadView(numpadView: NumpadView)
}
class NumpadView: UIButton{
var pressDelegate: NumpadPressDelegateProtocol?
init(char: Character) {
let frame = CGRectMake(160, 100, 50, 50)
super.init(frame:frame)
self.setTitle("\(char)", forState: UIControlState.Normal)
self.userInteractionEnabled = true
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
pressDelegate?.numpadView(self)
}
}
GameController.swift
class GameController: NumpadPressDelegateProtocol {
func numpadView(numpadView: NumpadView) {
//do something
}
}
Declaring GameController as NumpadPressDelegateProtocol is not enough for you to get a callback. You also need to set the pressDelegate of the NumpadView instance inside the Gamecontroller. Assuming numpadView is the instance variable be it IBOutlet or not, you have to set the delegate like
Inside GameController init
numpadView.pressDelegate = self
Have you set the pressDelegate property to something? Nothing is assigned to it in the code you've shown. Do you assign something to it elsewhere in your code?

Resources