I have been trying and searching for something that will help me for a long time but I haven't been able to find a solution yet. I am just trying to save a high score for the game that I am making but it always shows no errors and then gives me weird errors like "Thread 1: signal SIGABRT" when i try and run. Can anyone help me see what I am doing wrong?
import CoreMotion
import SpriteKit
enum CollisionTypes: UInt32{
case Player = 1
case Wall = 2
case Star = 4
case Vortex = 8
case Finish = 16
}
var levelsPassed = 0
var levelName = "level1"
class GameScene: SKScene, SKPhysicsContactDelegate {
var player: SKSpriteNode!
//hack so that we can test on the computer and then use on devises as well
var lastTouchPosition: CGPoint?
//create the motion manager
var motionManager: CMMotionManager!
//score labels
var scoreLabel: SKLabelNode!
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
var highScoreLabel: SKLabelNode!
var highestScore:Int = 0
var gameOver = false
override func didMoveToView(view: SKView) {
/* Setup your scene here */
UIApplication.sharedApplication().idleTimerDisabled = true
let background = SKSpriteNode(imageNamed: "background.jpg")
background.position = CGPoint(x: 512, y: 384)
background.zPosition = -1
background.blendMode = .Replace
addChild(background)
NSUserDefaults.standardUserDefaults().setObject(highestScore, forKey:"HighestScore")
NSUserDefaults.standardUserDefaults().synchronize()
if (NSUserDefaults.valueForKey("HighestScore") != nil){
var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("HighestScore") as! Int
}
//call the loadLevel funciton
loadLevel(levelName)
createPlayer()
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.text = "Score: 0"
scoreLabel.horizontalAlignmentMode = .Left
scoreLabel.position = CGPoint(x:32, y:100)
scoreLabel.zPosition = 2
addChild(scoreLabel)
highScoreLabel = SKLabelNode(fontNamed: "Chalkduster")
highScoreLabel.text = "Highscore: \(highestScore)"
highScoreLabel.horizontalAlignmentMode = .Left
highScoreLabel.position = CGPoint(x:225, y:100)
highScoreLabel.zPosition = 2
addChild(scoreLabel)
//give the game no gravity by default
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
motionManager = CMMotionManager()
motionManager.startAccelerometerUpdates()
}
Try this code
import SpriteKit
class GameScene: SKScene {
var highScoreLabel: SKLabelNode!
var highestScore:Int = 0
var score = 0
override func didMoveToView(view: SKView) {
highScoreLabel = SKLabelNode(fontNamed: "Chalkduster")
highScoreLabel.text = "Highscore: \(highestScore)"
highScoreLabel.horizontalAlignmentMode = .Left
highScoreLabel.position = CGPoint(x:225, y:100)
highScoreLabel.zPosition = 2
addChild(highScoreLabel)
}
override func update(currentTime: NSTimeInterval) {
var highscore = 1
let userDefaults = NSUserDefaults.standardUserDefaults()
highscore = userDefaults.integerForKey("highscore")
userDefaults.setValue(highscore, forKey: "highscore")
if score > highscore {
userDefaults.setValue(score, forKey: "highscore")
}
highScoreLabel.text = "highscore: \(highscore)"
userDefaults.synchronize()
}
}
Related
I have a maze game that I coded with swift that does not save levels. Currently, when the user closes the app, nothing is saved and the user has to start playing the game from level 1 again. I have a different .swift and .sks file for every level, so I am not sure how to save level data across classes/files.
I have tried to use UserDefaults, however, I am not sure how to save the "file path" to my level. I know that I need to implement something in my AppDelegate (using the applicationWillTerminate or applicationDidEnterBackground func), however, I am not sure what code (if any) I need to put in the scenes themselves to save this data. I have not worked with saving user data before, so help would be greatly appreciated!
import SpriteKit
import GameplayKit
import CoreMotion
import SceneKit
import UIKit
class GameScene: SKScene, SKPhysicsContactDelegate {
let gameScene = SKScene()
var button: SKNode! = nil
var playerSprite = SKSpriteNode()
var nextNode = SKSpriteNode()
lazy var countdownLabel: SKLabelNode = {
var label = SKLabelNode(fontNamed: "Helvetica")
label.horizontalAlignmentMode = .center
label.verticalAlignmentMode = .center
label.color = UIColor.red
label.text = "\(counter)"
return label
}()
var counter = 30
var counterTimer = Timer()
var counterStartValue = 30
let motionManager = CMMotionManager()
override func didMove(to view: SKView) {
self.scene?.scaleMode = SKSceneScaleMode.aspectFit
button = SKSpriteNode(imageNamed: "redoButton")
button.position = CGPoint(x: 350, y: 585);
self.addChild(button)
countdownLabel.position = CGPoint(x: 0.5, y: 0.5)
addChild(countdownLabel)
counter = counterStartValue
runTimer()
self.physicsWorld.contactDelegate = self
playerSprite = self.childNode(withName: "playerSprite") as! SKSpriteNode
nextNode = self.childNode(withName: "nextNode") as! SKSpriteNode
motionManager.startAccelerometerUpdates()
motionManager.accelerometerUpdateInterval = 0.1
motionManager.startAccelerometerUpdates(to: OperationQueue.main) {
(data,error) in
self.physicsWorld.gravity = CGVector(dx: CGFloat((data?.acceleration.x)!) * 10, dy: CGFloat((data?.acceleration.y)!) * 10)
}
}
func didBegin(_ contact: SKPhysicsContact) {
let bodyA = contact.bodyA
let bodyB = contact.bodyB
if bodyA.categoryBitMask == 1 && bodyB.categoryBitMask == 2 || bodyA.categoryBitMask == 2 && bodyB.categoryBitMask == 1{
playerSprite.removeFromParent()
nextNode.removeFromParent()
self.removeFromParent()
let transition = SKTransition.fade(withDuration: 0.5)
let gameScene2 = GameScene2(fileNamed: "GameScene2")
gameScene2!.scaleMode = SKSceneScaleMode.aspectFit
self.view?.presentScene(gameScene2!, transition: transition)
}
}
func runTimer() {
counterTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(decrementCounter), userInfo: nil, repeats: true)
}
#objc func decrementCounter() {
counter -= 1
countdownLabel.text = "\(counter)"
if countdownLabel.text! < "0" as String {
countdownLabel.text = "Game Over"
playerSprite.removeFromParent()
nextNode.removeFromParent()
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
if touch.view == self.button {
print("Yay!!!")
} else {
playerSprite.isHidden = false
nextNode.isHidden = false
let gameScene = GameScene(fileNamed: "GameScene")
gameScene!.scaleMode = SKSceneScaleMode.aspectFit
let transition = SKTransition.fade(withDuration: 0.5)
self.view?.presentScene(gameScene!, transition: transition)
}
}
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
save it with a string
UserDefaults.standard.set(StateOftheGame, forKey: "levelPass")
then on app delegate check if the user 'passLevel' when the game starts
in
didFinishLaunchingWithOptions -> add function passLevel()
func passLevel() {
if UserDefaults.standard.value(forKey: "levelPass") != nil
{
let VC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "YOURVIEWCONTROLLERWITHSAVESTATE")
let navVC = UINavigationController(rootViewController: VC)
let share = UIApplication.shared.delegate as? AppDelegate
share?.window?.rootViewController = navVC
share?.window?.makeKeyAndVisible()
}
}
I am trying to make a new level for my app. I am honestly just copy and pasting my code from the view controllers and gamescenes to other files that I changed the name of. Yes, I did change the names INSIDE the files too so It'll match the new level. However, my contact delegate won't work on my new level now. How can I fix this?
Cannot assign value of type 'Level1' to type 'SKPhysicsContactDelegate?'
What am I doing wrong? I just checked my main file that I had before creating a new level and it now has errors. I have't changed any of the coding.
import SpriteKit
import GameplayKit
class Level1: SKScene {
var ball = SKSpriteNode()
var danger1 = SKSpriteNode()
var danger2 = SKSpriteNode()
var goal = SKSpriteNode()
over
ride func didMove(to view: SKView) {
physicsWorld.contactDelegate = self
ball = self.childNode(withName: "ball") as! SKSpriteNode
danger1 = self.childNode(withName: "danger1") as! SKSpriteNode
danger2 = self.childNode(withName: "danger2") as! SKSpriteNode
goal = self.childNode(withName: "goal") as! SKSpriteNode
let border = SKPhysicsBody(edgeLoopFrom: self.frame)
border.friction = 0
border.restitution = 0
danger1.physicsBody = SKPhysicsBody(rectangleOf: danger1.size)
danger1.physicsBody?.categoryBitMask = PhysicsCategories.dangerCategory
danger1.physicsBody?.isDynamic = false
danger2.physicsBody = SKPhysicsBody(rectangleOf: danger2.size)
danger2.physicsBody?.categoryBitMask = PhysicsCategories.dangerCategory
danger2.physicsBody?.isDynamic = false
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)
ball.physicsBody?.categoryBitMask = PhysicsCategories.ballCategory
ball.physicsBody?.contactTestBitMask = PhysicsCategories.dangerCategory | PhysicsCategories.goalCategory
ball.physicsBody?.collisionBitMask = PhysicsCategories.none
ball.physicsBody?.isDynamic = true
ball.physicsBody!.affectedByGravity = false
goal.physicsBody = SKPhysicsBody(rectangleOf: goal.size)
goal.physicsBody?.categoryBitMask = PhysicsCategories.goalCategory
goal.physicsBody?.isDynamic = false
setupPhysics()
startGame()
}
func setupPhysics() {
physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)
physicsWorld.contactDelegate = self
}
func startGame() {
ball.position = CGPoint(x: 0, y: 550)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
ball.position.x = location.x
ball.position.y = location.y
}
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
extension GameScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
if contactMask == PhysicsCategories.ballCategory | PhysicsCategories.dangerCategory {
print("Contact")
} else if contactMask == PhysicsCategories.ballCategory | PhysicsCategories.goalCategory {
print("goal contact")
}
}
}
Instead of creating extension of GameScene, create extension of Level1
extension Level1: SKPhysicsContactDelegate
So I am creating an air hockey game and there are 5 major SKSpriteNodes. I need to detect collision between the puck and goal1 and goal2. When it does detect collision it needs to add 1 to the scoreLeft or scoreRight which are SKLabelNode's. I have used the Gamescene.sks file to make the visual representation. I commented the didBeginContact because thats where it doesn't work. Thank You in advance.
class GameScene: SKScene, SKPhysicsContactDelegate {
let paddle1CategoryName = "paddle1"
let paddle2CategoryName = "paddle2"
let puckCategoryName = "puck"
let goal1CategoryName = "goal1"
let goal2CategoryName = "goal2"
let scoreLeftCategoryName = "scoreLeft"
let scoreRightCategoryName = "scoreRight"
var isFingerOnPaddle1 = false
var isFingerOnPaddle2 = false
var paddle1Category: UInt32 = 0x1 << 0
var paddle2Category: UInt32 = 0x1 << 1
var puckCategory: UInt32 = 0x1 << 2
var goal1Category: UInt32 = 0x1 << 3
var goal2Category: UInt32 = 0x1 << 4
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody
let paddle1 = childNodeWithName(paddle1CategoryName) as! SKSpriteNode
let paddle2 = childNodeWithName(paddle2CategoryName) as! SKSpriteNode
let puck = childNodeWithName(puckCategoryName) as! SKSpriteNode
let goal1 = childNodeWithName(goal1CategoryName) as! SKSpriteNode
let goal2 = childNodeWithName(goal2CategoryName) as! SKSpriteNode
let scoreLeft = childNodeWithName(scoreLeftCategoryName) as! SKLabelNode
let scoreRight = childNodeWithName(scoreRightCategoryName) as! SKLabelNode
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
var touch = touches.first! as UITouch
var location = touch.locationInNode(self)
if let body = physicsWorld.bodyAtPoint(location){
if body.node!.name == paddle1CategoryName {
print("The game has begun.")
isFingerOnPaddle1 = true
} else if body.node!.name == paddle2CategoryName{
print("The game has begun.")
isFingerOnPaddle2 = true
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let paddle1 = childNodeWithName(paddle1CategoryName) as! SKSpriteNode
let paddle2 = childNodeWithName(paddle2CategoryName) as! SKSpriteNode
let puck = childNodeWithName(puckCategoryName) as! SKSpriteNode
let goal1 = childNodeWithName(goal1CategoryName) as! SKSpriteNode
let goal2 = childNodeWithName(goal2CategoryName) as! SKSpriteNode
var touch = touches.first! as UITouch
var touchLocation = touch.locationInNode(self)
var previousLocation = touch.previousLocationInNode(self)
if isFingerOnPaddle1{
let paddle1X = paddle1.position.x + (touchLocation.x - previousLocation.x)
let paddle1Y = paddle1.position.y + (touchLocation.y - previousLocation.y)
if (touchLocation.x <= paddle1.position.x && (touchLocation.y <= paddle1.position.y || touchLocation.y >= paddle1.position.y)){
paddle1.position = CGPoint(x: paddle1X, y: paddle1Y)
}
}
if isFingerOnPaddle2{
let paddle2X = paddle2.position.x + (touchLocation.x - previousLocation.x)
let paddle2Y = paddle2.position.y + (touchLocation.y - previousLocation.y)
if (touchLocation.x >= paddle2X && (touchLocation.y >= paddle2Y || touchLocation.y < paddle2.position.y)){
paddle2.position = CGPoint(x: paddle2X, y: paddle2Y)
}
}
}
/*
func didBeginContact(contact: SKPhysicsContact) {
let scoreLeft = childNodeWithName(scoreLeftCategoryName) as! SKLabelNode
let scoreRight = childNodeWithName(scoreRightCategoryName) as! SKLabelNode
var score = 0
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch contactMask{
case puckCategory | goal1Category:
if contact.bodyA.categoryBitMask == puckCategory{
puckCategory = contact.bodyA.categoryBitMask
goal1Category = contact.bodyB.categoryBitMask
score++
scoreRight.text = "\(score)"
}else{
puckCategory = contact.bodyB.categoryBitMask
goal1Category = contact.bodyA.categoryBitMask
score++
scoreRight.text = "\(score)"
}
case puckCategory | goal2Category:
if contact.bodyA.categoryBitMask == puckCategory{
puckCategory = contact.bodyA.categoryBitMask
goal2Category = contact.bodyB.categoryBitMask
score++
scoreLeft.text = "\(score)"
}else{
puckCategory = contact.bodyB.categoryBitMask
goal2Category = contact.bodyA.categoryBitMask
score++
scoreLeft.text = "\(score)"
}
default:
// Nobody expects this, so satisfy the compiler and catch
// ourselves if we do something we didn't plan to
fatalError("other collision: \(contactMask)")
}
}*/
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
One issue is using a local var score = 0 at the beginning of your function. Remove it. The score should be stored in the game's model so that logic about winning can be applied but matching your code, at least do this.
if let score = Int(scoreLeft.text) {
scoreLeft.text = "\(score + 1)"
}
Additionally there is a problem with
case puckCategory | goal1Category:
if contact.bodyA.categoryBitMask == puckCategory{
puckCategory = contact.bodyA.categoryBitMask
What you are saying is if contact.bodyA.categoryBitMask is equal to puckCategory, then set puckCategory to contact.bodyA.categoryBitMask. That is a no-op, nothing changes AND more importantly you don't want to change the bit masks that your child nodes are compared against. Make puckCategory, goal1Categoy, and goal2Category constants. Good luck.
Follow Up To OP Comment:
So, throw away the code in didBeginContact that set the category mask variables for two reasons. 1) Setting variables like puckCatergory to their same value is wasteful and confusing. 2) Since variables like puckCategory are compared to child node bit masks, it would be disasterous if they ever did change. That function should look like this. Also be sure and add handlers for the other types of contacts before you get too far.
func didBeginContact(contact: SKPhysicsContact) {
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch contactMask {
case puckCategory | goal1Category:
let scoreRight = childNodeWithName(scoreRightCategoryName) as! SKLabelNode
if let score = Int(scoreRight.text) {
scoreRight.text = "\(score + 1)"
}
case puckCategory | goal2Category:
let scoreLeft = childNodeWithName(scoreLeftCategoryName) as! SKLabelNode
if let score = Int(scoreLeft.text) {
scoreLeft.text = "\(score + 1)"
}
default:
// There are other contacts that need to be handled; paddle+puck,puck+wall, etc
fatalError("other collision: \(contactMask)")
}
}
My problem is I am trying to make all the bar6s to move down to the bottom of the screen, similar to flappy bird. I've done most of it, what I've done is make the bars go
down but I want to make it go on forever but only 5 bars go down how can I make it go on forever like regenerate or can you make a completion block in the function while you declare it.
Here is my code:
//
// PlaysScene.swift
// Pocket Rocket3
//
// Created by Lucas Farleigh on 27/11/2014.
// Copyright (c) 2014 Lucas Farleigh. All rights reserved.
//
import spriteKit
class PlayScene:SKScene {
//declaring the node in this scene!
let background = SKSpriteNode(imageNamed: "background")
let bar1 = SKSpriteNode(imageNamed:"bar1")
let bar2 = SKSpriteNode(imageNamed:"bar2")
let bar3 = SKSpriteNode(imageNamed:"bar3")
let bar4 = SKSpriteNode(imageNamed:"bar4")
let bar5 = SKSpriteNode(imageNamed:"bar5")
let bar6a = SKSpriteNode(imageNamed: "bar6")
let bar6b = SKSpriteNode(imageNamed: "bar6")
let bar6c = SKSpriteNode(imageNamed: "bar6")
let bar6d = SKSpriteNode(imageNamed: "bar6")
let bar6e = SKSpriteNode(imageNamed: "bar6")
let bar6f = SKSpriteNode(imageNamed: "bar6")
let bar6g = SKSpriteNode(imageNamed: "bar6")
let bar6h = SKSpriteNode(imageNamed: "bar6")
let bar6i = SKSpriteNode(imageNamed: "bar6")
let bar6j = SKSpriteNode(imageNamed: "bar6")
//making actions
override func didMoveToView(view: SKView) {
var check1 = false
var check2 = false
var check3 = false
var check4 = false
var check5 = false
var delayA = SKAction.waitForDuration(NSTimeInterval(1.5))
var delayB = SKAction.waitForDuration(NSTimeInterval(2))
var delayC = SKAction.waitForDuration(NSTimeInterval(4))
var delayD = SKAction.waitForDuration(NSTimeInterval(6))
var delayE = SKAction.waitForDuration(NSTimeInterval(8))
var actionmove = SKAction.moveToY(0, duration: 15)
var delay = SKAction.waitForDuration(NSTimeInterval(1.5))
var sequence = SKAction.sequence([ delay , actionmove])
var delchild = SKAction.removeFromParent()
func f1 () {
bar6a.position = CGPointMake(800 ,CGRectGetMaxY(self.frame))
bar6b.position = CGPointMake(1600,CGRectGetMaxY(self.frame))
check1 = false
bar6a.runAction(actionmove)
bar6b.runAction(actionmove,completion: {
self.bar6a.position = CGPointMake(800 ,CGRectGetMaxY(self.frame))
self.bar6b.position = CGPointMake(1600,CGRectGetMaxY(self.frame))
check1 = true
self.bar6a.runAction(actionmove)
self.bar6b.runAction(actionmove,completion: {
self.bar6a.removeFromParent()
self.bar6b.removeFromParent()
check1 = true
})
})
actionmove.timingMode = SKActionTimingMode.EaseOut
}
var sequence2 = SKAction.sequence([ delayB ,actionmove])
var sequence3 = SKAction.sequence([ delayC ,actionmove])
var sequence4 = SKAction.sequence([ delayD ,actionmove])
var sequence5 = SKAction.sequence([delayE , actionmove])
bar6a.xScale = 2.5
bar6b.xScale = 2.5
bar6c.xScale = 2.5
bar6d.xScale = 2.5
bar6e.xScale = 2.5
bar6f.xScale = 2.5
bar6g.xScale = 2.5
bar6h.xScale = 2.5
bar6i.xScale = 2.5
bar6j.xScale = 2.5
//making the actions
var num1 = 1
//making different delays
//sequence actions
addChild(bar6a)
addChild(bar6b)
addChild(bar6c)
addChild(bar6d)
addChild(bar6e)
addChild(bar6f)
addChild(bar6g)
addChild(bar6h)
addChild(bar6i)
addChild(bar6j)
//making the functions
func f2 () {
check2 = false
bar6c.position = CGPointMake(400 ,CGRectGetMaxY(self.frame))
bar6d.position = CGPointMake(1200,CGRectGetMaxY(self.frame))
bar6d.runAction(sequence2)
bar6c.runAction(sequence2, completion:{
self.bar6c.removeFromParent()
self.bar6d.removeFromParent()
check2 = true
})
bar6d.runAction(sequence2)
}
func f3 () {
check3 = false
bar6e.position = CGPointMake(600 ,CGRectGetMaxY(self.frame))
bar6f.position = CGPointMake(1400,CGRectGetMaxY(self.frame))
bar6e.runAction(sequence3,completion:{
self.bar6e.removeFromParent()
self.bar6f.removeFromParent()
check3 = true
})
bar6f.runAction(sequence3)
}
func f4 () {
check4 = false
bar6g.position = CGPointMake(700 ,CGRectGetMaxY(self.frame))
bar6h.position = CGPointMake( 1500,CGRectGetMaxY(self.frame))
bar6h.runAction(sequence4)
bar6g.runAction(sequence4,completion:{
self.bar6g.removeFromParent()
self.bar6h.removeFromParent()
check4 = true
})
}
func f5 () {
check5 = false
bar6i.position = CGPointMake(700 ,CGRectGetMaxY(self.frame))
bar6j.position = CGPointMake(1500 ,CGRectGetMaxY(self.frame))
bar6j.runAction(sequence5)
bar6i.runAction(sequence5,completion:{
check5 = true
self.bar6i.removeFromParent()
self.bar6j.removeFromParent()
})
}
f1()
f2()
f3()
f4()
f5()
//making the action repeat forever
var num2 = 1
bar1.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar2.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar3.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar4.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar5.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY (self.frame))
bar1.xScale = 2.5
bar2.xScale = 2.5
bar3.xScale = 2.5
bar4.xScale = 2.5
bar5.xScale = 1.7
/*
bar1.runAction(sequence, completion: {
self.bar2.runAction(sequence, completion: {
self.bar3.runAction(sequence, completion:{
self.bar4.runAction(sequence, completion:{
self.bar5.runAction(sequence)
})
})
})
})*/
background.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame))
//doing the background stuff
background.yScale = 2.0
background.xScale = 3.0
addChild(background)
//doing the the bar stuff
if check1 == true{
f1()
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
}
}
EDIT: I see that you are trying to do this similar to flappy bird now. I would suggest doing either an SKPhysicsNode with spritekit or attempting to use Cocos2d http://www.cocos2d-x.org/wiki/Physics
Hi I have been trying to do this for a long time,I am using Swift SpriteKit , my problem is that I need to make a runBlock action for a node how do I make an action which runs a function I have tried this:
var a = SKAction.runBlock({() in self.spawn1()})
For your information The spawn1 is the function.
Thanks in advance!
Heres my code for help of the comment of the first answer:
//
// PlaysScene.swift
// Pocket Rocket3
//
// Created by Lucas Farleigh on 27/11/2014.
// Copyright (c) 2014 Lucas Farleigh. All rights reserved.
//
import spriteKit
class PlayScene:SKScene {
//declaring the node in this scene!
let background = SKSpriteNode(imageNamed: "background")
let bar1 = SKSpriteNode(imageNamed:"bar1")
let bar2 = SKSpriteNode(imageNamed:"bar2")
let bar3 = SKSpriteNode(imageNamed:"bar3")
let bar4 = SKSpriteNode(imageNamed:"bar4")
let bar5 = SKSpriteNode(imageNamed:"bar5")
let bar6a = SKSpriteNode(imageNamed: "bar6")
let bar6b = SKSpriteNode(imageNamed: "bar6")
let bar6c = SKSpriteNode(imageNamed: "bar6")
let bar6d = SKSpriteNode(imageNamed: "bar6")
let bar6e = SKSpriteNode(imageNamed: "bar6")
let bar6f = SKSpriteNode(imageNamed: "bar6")
let bar6g = SKSpriteNode(imageNamed: "bar6")
let bar6h = SKSpriteNode(imageNamed: "bar6")
let bar6i = SKSpriteNode(imageNamed: "bar6")
let bar6j = SKSpriteNode(imageNamed: "bar6")
//making actions
override func didMoveToView(view: SKView) {
var actionmove = SKAction.moveToY(0, duration: 15)
var delay = SKAction.waitForDuration(NSTimeInterval(1.5))
var delchild = SKAction.removeFromParent()
func spawn1(){
bar6a.position = CGPointMake(800 ,CGRectGetMaxY(self.frame))
bar6b.position = CGPointMake(1600,CGRectGetMaxY(self.frame))
addChild(bar6a)
addChild(bar6b)
}
func spawn2 (){
bar6c.position = CGPointMake(400 ,CGRectGetMaxY(self.frame))
bar6d.position = CGPointMake(1200,CGRectGetMaxY(self.frame))
addChild(bar6c)
addChild(bar6d)
}
func spawn3 (){
bar6e.position = CGPointMake(600 ,CGRectGetMaxY(self.frame))
bar6f.position = CGPointMake(1400,CGRectGetMaxY(self.frame))
addChild(bar6e)
addChild(bar6f)
}
func spawn4 (){
bar6g.position = CGPointMake(700 ,CGRectGetMaxY(self.frame))
bar6h.position = CGPointMake(1500,CGRectGetMaxY(self.frame))
addChild(bar6g)
addChild(bar6h)
}
func spawn5 (){
bar6i.position = CGPointMake(700 ,CGRectGetMaxY(self.frame))
bar6j.position = CGPointMake(1500,CGRectGetMaxY(self.frame))
addChild(bar6i)
addChild(bar6j)
}
var a = SKAction.runBlock({ self.spawn1() })
var b = SKAction.runBlock(spawn2)
var c = SKAction.runBlock(spawn3)
var d = SKAction.runBlock(spawn4)
var e = SKAction.runBlock(spawn5)
var delayA = SKAction.waitForDuration(NSTimeInterval(1.5))
var delayB = SKAction.waitForDuration(NSTimeInterval(2))
var delayC = SKAction.waitForDuration(NSTimeInterval(4))
var delayD = SKAction.waitForDuration(NSTimeInterval(6))
var delayE = SKAction.waitForDuration(NSTimeInterval(8))
var sequence1 = SKAction.sequence([delayA,a,actionmove,delchild])
var sequence2 = SKAction.sequence([delayB,b,actionmove,delchild])
var sequence3 = SKAction.sequence([delayC,c,actionmove,delchild])
var sequence4 = SKAction.sequence([delayD,d,actionmove,delchild])
var sequence5 = SKAction.sequence([delayE,e,actionmove,delchild])
var repeat1 = SKAction.repeatActionForever(sequence1)
var repeat2 = SKAction.repeatActionForever(sequence2)
var repeat3 = SKAction.repeatActionForever(sequence3)
var repeat4 = SKAction.repeatActionForever(sequence4)
var repeat5 = SKAction.repeatActionForever(sequence5)
//actionmove: making it smooth
actionmove.timingMode = SKActionTimingMode.EaseOut
//doing stuff with the background
background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
background.yScale = 10.0
background.xScale = 10.0
addChild(background)
//running the actions
bar6a.runAction(repeat1)
bar6b.runAction(repeat1)
bar6c.runAction(repeat2)
bar6d.runAction(repeat2)
bar6e.runAction(repeat3)
bar6f.runAction(repeat3)
bar6g.runAction(repeat4)
bar6h.runAction(repeat4)
bar6i.runAction(repeat5)
bar6j.runAction(repeat5)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
}
}
var a = SKAction.runBlock({ self.spawn1() })
yournode.runAction(a)