Hello my question is simply how to unhide a button in GameScene. I have a segueToMainMenu button that is set up in storyboard.
This is how my GameViewController looks:
#IBOutlet weak var segueToMainMenu: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let scene = GameScene(size: view.bounds.size)
let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = false
scene.scaleMode = .AspectFill
skView.presentScene(GameScene(size: skView.bounds.size))
scene.viewController = self
self.segueToMainMenu.hidden = true
}
I set the button to hidden but now in my game I would like to unhide it when a lose func runs in GameScene since when the button is clicked it segues back to the main menu which is a separate view controller also created in the storyboard. Anything helps thank you.
You either can create a delegate for you scene which will call appropriate method on gameOver and do something like
// in the view controller
func gameSceneDidSendGameOver() {
self.segueToMainMenu.hidden = false
}
//in the scene
var gameOverDelegate : GameOverDelegate?
func gameOver() {
gamOverDelegate?.gameSceneDidSendGameOver()
}
Or do it a little bit of ugly way like:
func gameOver() {
let gvc = self.viewController as GameViewController
gvc.segueToMainMenu.hidden = false
}
Edit: Declaration of the delegate protocol.
protocol GameOverDelegate {
func gameSceneDidSendGameOver()
}
class GameViewController : ViewController, GameOverDelegate {
...
func gameSceneDidSendGameOver() {
self.segueToMainMenu.hidden = false
}
}
Related
I want to call a func of GameViewController from the GameScene.
-> If the game Ends I want to call GameViewController().GameOver()
I tried now a lot of different things like this one: LINK (I tried every answer more than once, still not working)
But doesn't matter what I tried it doesn't even call the func.
Hope anyone can help me with this.
CODE:
GameViewController:
class GameViewController: UIViewController {
#IBOutlet weak var Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = GameScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
if UIDevice().userInterfaceIdiom == .phone {
scene.scaleMode = .aspectFill
}else{
scene.scaleMode = .aspectFit
}
// Present the scene
view.presentScene(scene)
skView = view
}
view.ignoresSiblingOrder = true
view.showsFPS = false
view.showsNodeCount = false
}
...
#IBAction func Button(_ sender: Any) {
animation()
if let gameScene = skView.scene as? GameScene { // check to see if the current scene is the game scene
gameScene.start()
}
}
func animation(){
UIButton.animate(withDuration: 1, animations: {
self.Button?.alpha = 0
})
}
func GameOver(){
UIButton.animate(withDuration: 1, animations: {
self.Button?.alpha = 1
})
}
}
GameScene:
class GameScene: SKScene, SKPhysicsContactDelegate {
...
func torpedoDidCollideWithAlien (torpedoNode:SKSpriteNode, alienNode:SKSpriteNode) {
GameViewController().GameOver()
removeAllActions()
removeAllChildren()
}
}
Option 1:
You should pass GameViewController instance when you are calling GameScene from GameViewController at the first time, Then just save this instance in some var gameVC: GameViewController! and initialize it like you do in prepare for segue method.
Then you'll be able to call gameVC.GameOver()
Option 2:
Put this in GameScene when you want to call GameOver():
if let controller = self.view?.window?.rootViewController as? GameViewController {
controller.GameOver()
}
I'm creating a Swift project for a high school programming class. I can't seem to figure out this problem, and everyone else in my class doesn't seem to have any ideas.
To start, I created a new Swift project, and chose a game format.
I then used some basic code to make the first level for my game, a maze game where the maze moves around instead of the ball based on how the user tilts the device.
This is my GameScene.swift:
import SpriteKit
import CoreMotion
var accelupdateinterval = 0.1
var accelmultiplier = 15.0
class GameScene: SKScene {
let manager = CMMotionManager()
override func didMoveToView(view: SKView) {
manager.startAccelerometerUpdates()
manager.accelerometerUpdateInterval = accelupdateinterval
manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()){
(data, error) in
self.physicsWorld.gravity = CGVectorMake(CGFloat((data?.acceleration.x)!) * CGFloat(accelmultiplier), CGFloat((data?.acceleration.y)!) * CGFloat(accelmultiplier))
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
I want to have a main menu that the app opens into, which is mainMenu.storyboard:
I successfully have the app launching into the mainMenu.storyboard (and the level physics work well when I've tested the level1.sks), but I'm having trouble figuring out how to segue.
GOAL: I want people to be segued into the level1.sks (and the levels that I add later), when they tap the corresponding image in mainMenu.storyboard.
I can't use the method of adding a Storyboard Reference to segue it, as the Storyboard Reference won't let me choose level1.sks.
I'd also love to find out how to send users back to the main menu when the player icon touches the goal (the blue thing up near the top in this screenshot):
So to do this I think the best approach is to create another ViewController subclass, maybe named LauncherViewController, which will present your SKScene. Then in your storyboard add this viewController and have your menu segue to it on an image press.
Here is a start for the LauncherViewController
class LauncherViewController: UIViewController {
var gameScene: GameScene!
override func viewDidLoad() {
}
override func viewWillAppear() {
presentGameScene()
}
func presentGameScene(){
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
skView.ignoresSiblingOrder = true
gameScene.size = skView.bounds.size
gameScene.scaleMode = .AspectFill
skView.presentScene(gameScene)
}
}
Where in your menu controller you have a prepareForSegue like this:
override func prepareForSegue(segue: UIStoryBoardSegue, sender: AnyObject?) {
if segue.identifier == "yourSegue" {
let destinationViewController = segue.destinationViewController as! LauncherViewController
destinationViewController.gameScene = GameScene()
}
to have your LauncherViewController dismiss the gameScene when the user finishes the maze, use a delegate pattern. So in GameScene add a protocol above your class
protocol GameDelegate {
func gameFinished()
}
have your LauncherViewController conform to this delegate and set the gameScene's delegate variable to self (see below)
class LauncherViewController: UIViewController, GameDelegate {
var gameScene: GameScene!
override func viewDidLoad() {
gameScene.delegate = self
}
override func viewWillAppear() {
presentGameScene()
}
func presentGameScene(){
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
skView.ignoresSiblingOrder = true
gameScene.size = skView.bounds.size
gameScene.scaleMode = .AspectFill
skView.presentScene(gameScene)
}
func gameFinished(){
// this forces LauncherViewController to dismiss itself
dismissViewControllerAnimated(true, completion: nil)
}
}
add a variable in GameScene to hold the delegate (LauncherViewController) and add a function that calls the delegate function. You will also need to add the logic to know when the game is over as I haven't done that.
class GameScene: SKScene {
let manager = CMMotionManager()
var delegate: GameDelegate!
override func didMoveToView(view: SKView) {
manager.startAccelerometerUpdates()
manager.accelerometerUpdateInterval = accelupdateinterval
manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()){
(data, error) in
self.physicsWorld.gravity = CGVectorMake(CGFloat((data?.acceleration.x)!) * CGFloat(accelmultiplier), CGFloat((data?.acceleration.y)!) * CGFloat(accelmultiplier))
}
}
func gameOver(){
delegate.gameFinished()
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
// it's probably easiest to add the logic for a gameOver here
if gameIsOver {
gameOver()
}
}
}
There will probably be some mistakes in here as I wrote this on my phone so just comment below for anything you are unsure about or doesn't work.
I have two views, the initial one that works fine, and a second one that I am trying to display after I transition to it from a button on the first view.
However, when I click the button, the transition happens and the screen goes blank.
Below is the viewDidLoad inside of the UIViewController class for the second view.
Also when it hits the
let sKView = view as! SKVIEW
line it spits out
Could not cast value of type 'UIView' (0x10a313eb0) to 'SKView' (0x1094d5718).
(lldb)
How do I get it to display the view?
class PlayViewController: UIViewController {
var scene2: PlayScene!
override func viewDidLoad() {
super.viewDidLoad()
let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
scene2 = PlayScene(size: skView.bounds.size)
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene2.scaleMode = .AspectFill
skView.presentScene(scene2)
}
first class
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? 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)
}
}
the second scene
import SpriteKit
class PlayScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "SCENE 2!";
myLabel.fontSize = 65;
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.position = location
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
sprite.runAction(SKAction.repeatActionForever(action))
self.addChild(sprite)
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
The issue is your view controllers view is your everyday run of the mill UIView instead of an SKView. Assuming you are using a storyboard click on the view controller and then click on the view and change the class to SKView instead of UIView.
Hopefully that helps.
I am not sure what are you trying to archive, you can try change your super class from UIViewController to SpriteViewController or you can create a new SKView and append to your view.
You cannot downcast a UIView to a SKView as a SKView inherit from UIView as you can see in the apple documentation
Inherits From
NSObject
UIResponder
UIView
SKView
so i found some posts about transitioning from Skscene to uiviewcontroller and I got it to work. This segue and unwind segue is called everytime the user win the level of my game or loses.
this works for level1 but as soon as I win level2 I get
fatal error: unexpectedly found nil while unwrapping an Optional value
on the line where I call the game over function below
in my game scene I have :
class GameScene: SKScene, SKPhysicsContactDelegate {
//next level / try again segue
var viewController : GameViewController!
in the GameViewController i initialize this property
var currentLevel: Int!
override func viewDidLoad() {
super.viewDidLoad()
currentLevel = gameScene.currentLevel
if let scene = GameScene.level(currentLevel) {
// 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)
//initialize VC
scene.viewController = self
}
func gameOver() {
performSegueWithIdentifier("gameOver", sender: nil)
}
#IBAction func perpareForUnwind(unwindSegue: UIStoryboardSegue) {
}
and finally i call gameOver from my win() function in gameScene
func newGame() {
view!.presentScene(GameScene.level(currentLevel))
}
func win() {
if (currentLevel < 3) {
currentLevel++
//present win view - with option to restart, next level, or home
}
println(currentLevel)
runAction(SKAction.sequence([SKAction.waitForDuration(2),
SKAction.runBlock(newGame)]))
self.viewController.gameOver() // this is the error!
}
So this works from level1 to level2 but wont work from level2 to level3
Since viewDidLoad is only called once it is only initialized from lvl1 to lvl2 and then becomes nil. How can i make sure that it is initialized everytime. Shoud I put this set up code somewhere other than viewDidLoad?
From level 1 to level 2 your var viewController is not nil, because you initialize it to self on viewDidLoad.
But then, on your next level, viewController is nil, because your code
//initialize VC
scene.viewController = self
only gets executed on viewDidLoad in your GameViewController.
You should set the value of your var viewController in your scene init method or didMoveToView, so it gets set for every new scene.
I am making a simple game in SpriteKit, and I am trying to make a main menu using UIKit. I created a View controller for the main menu and a separate one for the game. Whenever the play button is pressed, it switches to the Game view controller, where that then presents the first scene. However, whenever it seems that whenever it attempts to cast the game view controller's UIView to and SKView to be able to present the scene, something fails, and crash report is assembly, which I have no idea how to debug. I believe it is instantiating the game view controller twice, because when I put a println() in the viewWillLayoutSubviews() method, it prints twice. Another post on this said the type was already of SKView during the cast, causing it to fail, in which case that might mean when it triggers twice, it casts once, then tries to cast again and fails. Thanks in advance!
Here is the swift code
import UIKit
import SpriteKit
class MenuViewController: UIViewController {
let background = UIImageView(image: UIImage(named: "background.png"))
let titleImg = UIImageView(image: UIImage(named: "title.png"))
override func viewDidLoad() {
background.frame = self.view.frame
titleImg.frame = CGRectMake(0, 0, self.view.frame.width, 100)
self.view.addSubview(background)
self.view.addSubview(titleImg)
let bp = ButtonPositions(controller: self)
let play = button(bp.playY, named: "playButton.png")
let leader = button(bp.leaderY, named: "leaderButton.png")
let rate = button(bp.rateY, named: "rateButton.png")
play.addTarget(self, action: "playPressed", forControlEvents: UIControlEvents.TouchDown)
leader.addTarget(self, action: "leaderPressed", forControlEvents: UIControlEvents.TouchDown)
rate.addTarget(self, action: "ratePressed", forControlEvents: UIControlEvents.TouchDown)
self.view.addSubview(rate)
self.view.addSubview(leader)
self.view.addSubview(play)
}
func button(y:CGFloat, named name:String!) -> UIButton {
let bp = ButtonPositions(controller: self)
let img = UIImage(named: name)
let b = UIButton(frame: CGRectMake(bp.x, y, self.view.frame.width / 1.5, img.size.height))
b.setImage(img, forState: UIControlState.Normal)
return b
}
func playPressed() {
println("playPressed") //only prints once
changeVC()
}
func changeVC() {
self.presentViewController(GameViewController(), animated: true, completion: nil) //maybe initializing the GameViewController twice for some reason?
}
func leaderPressed() {
}
func ratePressed() {
}
func center() -> CGPoint {
return CGPoint(x: CGRectGetMidX(self.view.frame), y: CGRectGetMidY(self.view.frame))
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
class GameViewController: UIViewController {
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
//prepareGame()
println("test") //this prints twice, even through the button press event is only triggered once
}
func prepareGame() {
let skView = self.view as SKView //crashes here when called
let scene = GameScene(size: self.view.bounds.size)
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw())
} else {
return Int(UIInterfaceOrientationMask.All.toRaw())
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prefersStatusBarHidden() -> Bool {
return false
}
}
I had the same issue. I created my project using the default Swift Game project for iOS which by default created the project for SceneKit, since I want to use SpriteKit and tried casting my new scene to SKView it produced EXC_BAD_ACCESS at the line were I tried to cast. To fix my problem I had to change the Class in the main storyboard to SKView since it was defaulted to SCNView.
Steps I followed to fix:
Select the main storyboard (in my case it was Main.storyboard)
Select the view from the hierarchy under View Controller
Select the Identity inspector tab (Utilities panel on the right)
Under the Custom Class section change the class from SCNView to SKView
After doing this the issue went away.
This is not the most optimal way, but a temporary workaround was to create a new SKView and add it to the view controller's view. I was trying to avoid this because right at start of the scene the fps is around 40, and i see no reason why it shouldn't be 60 when there is nothing on the screen.
EDIT: adding a counter since the method was being called twice also helped with the fps
private var count = 0
private func prepareGame() {
count++
if count == 2 {
let skView = SKView(frame: self.view.frame)
self.view.addSubview(skView)
let scene = GameScene(size: skView.bounds.size)
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}