How can I flash the whole screen? - swift

I wanted to know how can the the screen flash when I touch the screen. I had tried to colorizeWhitColor but it only colorized the background, and I don't know how to return to the same color.
scene?.runAction(SKAction.colorizeWithColor(UIColor.blackColor(), colorBlendFactor: 1.0, duration: 0.5))
class GameViewController: UIViewController {
let viewFlash = UIView.init(frame: UIScreen.mainScreen().bounds)
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
/* 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)
viewFlash.hidden = true
self.view.addSubview(viewFlash)
}
func flashScreen(color: UIColor, flashTime: NSTimeInterval){
viewFlash.backgroundColor = color
viewFlash.hidden = false
NSTimer.scheduledTimerWithTimeInterval(flashTime, target: self, selector:#selector(ViewController.stopFlash), userInfo: nil, repeats: false) //here it tells me that
}
func stopFlash(){
viewFlash.hidden = true
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
if gameStarted == false {
flashScreen(UIColor.whiteColor(), 0.1)
circuloVerde.removeFromParent()
circuloMorado.removeFromParent()
circuloRojo.removeFromParent()
circuloBlanco.removeFromParent()
enemigoTimer = NSTimer.scheduledTimerWithTimeInterval(0.685, target: self, selector: Selector("enemigos"), userInfo: nil, repeats: true)
gameStarted = true
circuloPrincipal.runAction(SKAction.scaleTo(0.44, duration: 0.5))
score = 0
scoreLabel.text = "\(score)"
hits = 0
highscoreLabel.runAction(SKAction.fadeOutWithDuration(0.5))
}
}

In GameViewController.swift:
import UIKit
import SpriteKit
class GameViewController: UIViewController {
let viewFlash = UIView.init(frame: UIScreen.mainScreen().bounds)
override func viewDidLoad() {
super.viewDidLoad()
viewFlash.hidden = true
self.view.addSubview(viewFlash)
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
/* 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)
}
}
func flashScreen(color: UIColor, flashTime: NSTimeInterval){
viewFlash.backgroundColor = color
viewFlash.hidden = false
NSTimer.scheduledTimerWithTimeInterval(flashTime, target: self, selector:#selector(self.stopFlash), userInfo: nil, repeats: false)
}
func stopFlash(){
viewFlash.hidden = true
}
}
In GameScene.swift:
import SpriteKit
class GameScene: SKScene {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
if gameStarted == false {
//This is the new part
var parentVC = view?.window?.rootViewController as! GameViewController
parentVC.flashScreen(UIColor.whiteColor(), flashTime: 0.1)
//This is the new part
circuloVerde.removeFromParent()
circuloMorado.removeFromParent()
circuloRojo.removeFromParent()
circuloBlanco.removeFromParent()
enemigoTimer = NSTimer.scheduledTimerWithTimeInterval(0.685, target: self, selector: Selector("enemigos"), userInfo: nil, repeats: true)
gameStarted = true
circuloPrincipal.runAction(SKAction.scaleTo(0.44, duration: 0.5))
score = 0
scoreLabel.text = "\(score)"
hits = 0
highscoreLabel.runAction(SKAction.fadeOutWithDuration(0.5))
}
}
}

Related

SpriteKit Main Menu button issue

Wondering if you could help, I created a main menu with a background and button node. When I tap on the PLAY button, the game does not navigate to my GameScene and instead calls my print statement. Here is the code below:
import Foundation
import SpriteKit
import GameplayKit
class MainMenu: SKScene, SKPhysicsContactDelegate {
override func didMove(to view: SKView) {
background()
playButton()
}
func background()
{
let back = SKSpriteNode(imageNamed: "MainMenu")
back.anchorPoint = CGPoint(x: 0, y: 0)
back.zPosition = 1
back.size = CGSize(width: frame.width,height: frame.height)
back.name = "Background"
addChild(back)
}
func playButton()
{
let button = SKSpriteNode(imageNamed: "button")
button.zPosition = 2
button.name = "Play Button"
button.position = CGPoint(x: frame.width/2, y: frame.height/2)
button.setScale(0.3)
addChild(button)
}
func loadGame(){
guard let skView = self.view as SKView? else{
print("Could not get Skview")
return
}
guard let scene = GameScene(fileNamed: "GameScene") else {
print("Error Getting GameScene")
return
}
//let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
skView.showsPhysics = true
scene.scaleMode = .aspectFill
skView.presentScene(scene)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else{
return
}
let touchLoation = touch.location(in: self)
let touchNodes = nodes(at: touchLoation)
let firstTouchedNode = atPoint(touchLoation).name
print(firstTouchedNode)
if firstTouchedNode == "Play Button"{
loadGame()
}
}
}
func loadGame(){
guard let skView = self.view as SKView? else{
print("Could not get Skview")
return
}
var scene:SKScene = GameScene(size: self.size)
}
//let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
skView.showsPhysics = true
scene.scaleMode = .aspectFill
var transition:SKTransition = SKTransition.fadeWithDuration(1)
self.view?.presentScene(scene, transition: transition)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let node = self.atPoint(location)
if node.name == "Play Button"{
//when playbutton is pressed execute code here
loadGame()
}
}

SpriteKit - SpriteNode never shows

I am attempting to learn SpriteKit. I want to add a rectangle/square to the scene in code; but the item never shows;
All I want to do is add a white square to the screen, but find that it never adds.
In a breakpoint, I notice that didMove() never seems to get called.
What am I doing wrong?
class GameScene: SKScene {
override func didMove(to view: SKView) {
let item = SKSpriteNode(color: .white, size: CGSize(width: 150, height: 200))
item.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
self.addChild(item)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
update
I did not change the view controller generated by xcode
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
There is no GameScene.sks, I deleted this file as I do not want to use sks files
If a breakpoint in didMove(to view:) is never reached, then definitely your ViewController doesn't present the scene for some reason. Can you open your ViewController's file (e.g. GameViewController.swift) and see if you have any of those lines there (or anything to that effect):
let viewSize = UIScreen.main.bounds.size
let scene = GameScene(size: viewSize)
let skView = self.view as! SKView
skView.presentScene(scene)
Turns out view controller was not presenting the scene and changing it to this, following code posted by #Stoyan worked and I saw my sprite showing
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
let viewSize = UIScreen.main.bounds.size
let scene = GameScene(size: viewSize)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
view.presentScene(scene)
}

Make iAd correct for the Submit for the AppStore

I develop a SpriteKit Game for the AppStore and I add iAd to the App but when I run the App the iAd sometimes close and open again. Is it correct for the Submit for the AppStore or did I have to change something in the code.
var UIiAd: ADBannerView = ADBannerView()
var SH = UIScreen.mainScreen().bounds.height
var BV: CGFloat = 0
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)
}
}
// 1
func appdelegate() -> AppDelegate {
return UIApplication.sharedApplication().delegate as! AppDelegate
}
// 2
override func viewWillAppear(animated: Bool) {
print("Showing ad")
BV = UIiAd.bounds.height
UIiAd.delegate = self
UIiAd = self.appdelegate().UIiAd
UIiAd.frame = CGRectMake(0, SH - BV, 0, 0)
self.view.addSubview(UIiAd)
self.view.addSubview(UIiAd)
}
override func viewWillDisappear(animated: Bool) {
UIiAd.delegate = nil
UIiAd.removeFromSuperview()
}
// 4
func bannerViewDidLoadAd(banner: ADBannerView!) {
print("ad loaded")
UIiAd.frame = CGRectMake(0, SH + 50, 0, 0)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
UIiAd.alpha = 1
UIiAd.frame = CGRectMake(0, SH - 50, 0, 0)
UIView.commitAnimations()
}
// 5
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
print("failed to receive ad")
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0)
UIiAd.alpha = 1
UIView.commitAnimations()
}
It is OK. Depending on the availability of a (new) ad iAd will hide the banner view.

remove UIGestures when leaving scene

I am having problems with my UIGestures in my game
At the gamescene, they work perfect, but when I move to another scene the UIgestures keep active and if I use them(swipe) than it crashes.
I know I have to use willmovefromview method in Gamescene file but have been working 2 days on this and still not working..
here is my viewcontroller file: (see comments for the gesture functions and gesture recognizers)
import UIKit
import SpriteKit
import AVFoundation
class GameViewController: UIViewController, UITextFieldDelegate{
//gesture functions
func swipedRight(sender: UISwipeGestureRecognizer){
let skView = view as SKView
let gameScene = skView.scene as GameScene
gameScene.swipedRight1(sender)
}
func swipedLeft(sender: UISwipeGestureRecognizer){
let skView = view as SKView
let gameScene = skView.scene as GameScene
gameScene.swipedLeft1(sender)
}
func swipedDown(sender: UISwipeGestureRecognizer){
let skView = view as SKView
let gameScene = skView.scene as GameScene
gameScene.swipedDown1(sender)
}
func swipedUp(sender: UISwipeGestureRecognizer){
let skView = view as SKView
let gameScene = skView.scene as GameScene
gameScene.swipedUp1(sender)
}
override func viewDidLoad() {
super.viewDidLoad()
let skView = view as SKView
skView.multipleTouchEnabled = false
scene = GameMenuScene(size: skView.bounds.size)
//scene.scaleMode = SKSceneScaleMode.ResizeFill
skView.showsFPS = true
skView.showsNodeCount = true
skView.presentScene(scene)
//Gesture recognizers
let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedRight:"))
swipeRight.direction = .Right
view.addGestureRecognizer(swipeRight)
let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedLeft:"))
swipeLeft.direction = .Left
view.addGestureRecognizer(swipeLeft)
let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedUp:"))
swipeUp.direction = .Up
view.addGestureRecognizer(swipeUp)
let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedDown:"))
swipeDown.direction = .Down
view.addGestureRecognizer(swipeDown)
}
override func viewDidLayoutSubviews() {
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
PS: My app is starting on a menuscene, and the swipes must only be active at the gamescene, so I think I have to use didmovetoview method as well.
and here are the didmovetoview method and willmovefromview method on my gamescene file:
override func didMoveToView(view: SKView) {
}
override func willMoveFromView(view: SKView) {
}
Who is going to help me?
Thanks in advance
override func willMoveFromView(view: SKView) {
for recognizer in self.view.gestureRecognizers! {
self.view.removeGestureRecognizer(recognizer)
}
}
self.view.gestureRecognizers=nil;
It works for me.

Dismissing GameCenter View in Swift

After showing a Game Center view it doesn't dismiss after tapping done. Here's my code to show it:
let gameCenterController = GKGameCenterViewController()
self.presentViewController(gameCenterController, animated:true, completion: nil)
What am I missing?
There is some good Q&A on this over at Ray Wenderlich. See the last method in the code below. Source:
http://www.raywenderlich.com/forums/viewtopic.php?f=2&t=18671
class GameViewController: UIViewController, GKGameCenterControllerDelegate {
var skView: SKView!
var scene: GameScene!
override func viewDidLoad() {
super.viewDidLoad()
// View
//------
skView = self.view as SKView
skView.ignoresSiblingOrder = true
scene = GameScene.sceneWithSize(skView.bounds.size)
scene.scaleMode = .AspectFill
scene.view?.window?.rootViewController = self
skView.presentScene(scene)
authenticateLocalPlayer()
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
var touch:UITouch = touches.anyObject() as UITouch
var location:CGPoint = touch.locationInNode(scene)
if (scene.gameCenterRect.contains(location) && GKLocalPlayer.localPlayer().authenticated) {
self.openGameCenter()
}
}
func openGameCenter() {
var gameCenter = GKGameCenterViewController()
gameCenter.gameCenterDelegate = self
self.presentViewController(gameCenter, animated: true, completion: nil)
}
func authenticateLocalPlayer(){
var localPlayer = GKLocalPlayer()
localPlayer.authenticateHandler = {(viewController, error) -> Void in
if ((viewController) != nil) {
self.presentViewController(viewController, animated: true, completion: nil)
}else{
println("(GameCenter) Player authenticated: \(GKLocalPlayer.localPlayer().authenticated)")
}
}
}
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!) {
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
[...] // standard methods
}