Menu
  • HOME
  • TAGS

Decreasing accelerometer's sensitivity

ios,swift,sprite-kit,accelerometer,core-motion

Try: let multiplier = 200.0 let x = data.acceleration.x if x > 0.2 { square.physicsBody!.velocity = CGVector(dx: x * multiplier, dy: -200) } else if x < 0.2 { square.physicsBody!.velocity = CGVector(dx: x * multiplier, dy: -200) } The above will vary the speed of the node depending on how...

Write a text in a circle in Sprite kit (swift)

swift,sprite-kit,skshapenode

One way to drag both at once is you can add both into same view and after that you change position of both with touch events like show into below code. import SpriteKit class GameScene: SKScene { var deltaPoint = CGPointZero let myLabel = SKLabelNode(fontNamed:"Chalkduster") var Circle = SKShapeNode(circleOfRadius: 100...

How can i make the lose label to appear once the timer hits zero?

ios,swift,timer,sprite-kit

Your code: if (timesecond == 0){ showMessage.hidden = false } ... should be in the block that runs every second: var actionwait = SKAction.runBlock({ self.timesecond-- if self.timesecond == 60 {self.timesecond = 0} self.ScoreLabel.text = "\(self.timesecond)" if (self.timesecond == 0){ showMessage.hidden = false } }) let loopAction = SKAction.repeatAction(SKAction.sequence([actionwait, actionrun]), count:...

How to call an object's methods in touchesBegan when touched?

objective-c,sprite-kit,touchesbegan

The issue is in your balloon init. Instead of using the Balloon class you are creating child SKSpriteNode and setting the name to balloon. This is why you are getting a SKSpriteNode and not a Balloon. You could do something like this instead. -(id)init{ self = [super init]; if (self){...

unwrapping SKPhysicsBody doesn't work

sprite-kit,skphysicsbody,forced-unwrapping

Well your applyRecurringForce method is declared in your custom node class (RocketMaker), not the SKPhysicsBody class. So you need to change the inside of your for-loop to this: println("physicsBody: \(rocketNode.physicsBody!.description)") rocketNode.applyRecurringForce() Also i'm not really sure what rocketShips is. I originally though it was an array but given that you...

UIScrollView in sprite kit

ios,objective-c,iphone,uiscrollview,sprite-kit

To do so, make use of NSNotificationCenter 1: In viewDidLoad() add this NSNotificationCenter.defaultCenter().addObserver(self, selector: "Facebook", name: "FacebookShare", object: nil) 2: In the method whereby you want to pass a function from UIViewController toSKScene NSNotificationCenter.defaultCenter().postNotificationName("FacebookShare", object: nil) ...

SKAction runblock with arguments

ios,swift,sprite-kit

You are on the right track. You should be able to use SKAction.runBlock({ self.someFunction(param) }) See the documentation for more details. ...

How to make a segue from SpriteKit GameScene to UIViewController programmatically in iOS 9 with Swift2

sprite-kit,segue,identifier,swift2,ios9

Segue identifiers are String objects, so you should call performSegueWithIdentifier with "push" instead of referencing it as a variable. This code should work: func segue(){ self.viewController.performSegueWithIdentifier("push", sender: viewController) } ...

Issue comparing UIColors in Swift

ios,swift,sprite-kit,uicolor

You can use "==" or isEqual. I have just tested both of them and they work fine: let redColor = UIColor.redColor() let greenColor = UIColor.greenColor() let blueColor = UIColor.blueColor() let testColor = UIColor.greenColor() println( testColor == redColor ) // false println( testColor == greenColor ) // true println( testColor ==...

Retain loop in a block

ios,objective-c,sprite-kit,objective-c-blocks,retain-cycle

You should definitely not ignore the warning, but use __weak instead to define a weak reference and eliminate retain cycles as described in the documentation: __weak SelfType *weakSelf = self; void (^aBlock)() = ^(){ SelfType *strongSelf = weakSelf; //User strongSelf }; Alternatively you can use libextobjc (https://github.com/jspahrsummers/libextobjc) with its convenient...

why isnt my second view loading after transition?

ios,swift,uiviewcontroller,sprite-kit

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....

How to put quotes around a string that has quotes?

string,swift,sprite-kit,quotes

Try this: let fruit = "\"apple\"" ...

Contact of Nodes with Subclass

ios,swift,sprite-kit

I found the solution, to fix my error i made the following: Remove the SKShapenode since the class is already a SKShapenode (that was the error). Then when creating my node i made everthing with self instead of putting in the Meteornode. That fixed all. Example: Right: self.position = CGPoint(x:...

Delete child SKSpriteNode

objective-c,iphone,sprite-kit,skspritenode

Here are some observations: You your code inside of a loop which only runs once. Why are you doing that? If you are creating an object, in your case a SKSpriteNode, and want to delete it later on, you will need to keep some kind of reference to it. There...

Spritekit animation doesn't work in iOS7 but does in iOS8

objective-c,sprite-kit,skaction

I see you're not setting zPosition. Make sure it contains what you expect. Apple made changes to the responder chain between iOS 7 and 8 so I wouldn't be surprised if they had changed how zPositions are initialised.

Action after tweet has been published

ios,twitter,sprite-kit

You can set a completion handler on your tweetSheet like so: [tweetSheet setCompletionHandler:^(SLComposeViewControllerResult result) { switch (result) { case SLComposeViewControllerResultCancelled: NSLog(@"Post Canceled"); break; case SLComposeViewControllerResultDone: NSLog(@"Post Sucessful"); break; default: break; } }]; ...

show menu when paused a game ins spritekit

swift,sprite-kit

I had solve my problem. While paused the game, all screen freezed however gamescene still detect all "touch" and if it has node name then we can do some operations. At this point, the proble is only showing my menu. So here is my solution.before I paused game, i added...

sprite kit : contact not working

ios,sprite-kit

I can produce good results with your code if I change the way of defining categories. Try setting categories like this : let ballcatagery: UInt32 = 0x1 << 0 // Not that you have misspelled word "category", which can lead to errors if you expect somewhere a word "category" instead...

SpriteKit share button not workiing

ios,objective-c,sprite-kit,share

I believe the issue is that you are creating a new GameViewController and because you are doing that it is crashing. Looks like it has something to do with the fact it can't find a SKView because it isn't being loaded from a storyboard. With that being said you don't...

How do you tell if a node is on the screen spritekit swift

swift,sprite-kit

You can use the following to test if a node is in the scene: if (!intersectsNode(sprite)) { println("node is not in the scene") } This assumes that self is an SKScene subclass, such as GameScene....

Start the transition after 5 seconds

swift,sprite-kit

You could use SKAction.waitForDuration combined with SKAction.runBlock in an SKAction sequence: let wait = SKAction.waitForDuration(5) let action = SKAction.runBlock { view?.presentScene(nextLevel, transition: transitionType) } self.runAction(SKAction.sequence([wait, action])) ...

How to access single sprite in array of sprites?

objective-c,sprite-kit,skspritenode

To access the first object in an array of sprites you can do this: SKSpriteNode *object = [myArray firstObject]; object.position = CGPointMake(arc4random_uniform(self.frame.size.width), arc4random_uniform(self.frame.size.height)); To access all objects in an array do this: for(SKSpriteNode *object in myArray) { object.position = CGPointMake(arc4random_uniform(self.frame.size.width), arc4random_uniform(self.frame.size.height)); } ...

Switching sprite positions with each other

ios,swift,sprite-kit

The way you have it setup now will make every pipe position the same because it will be referencing the same random index number you've generated with randomNumberBetween0And6. Put this in a loop and generate a new random number each time. You could also use a Tuple to swap the...

SKShapeNode is appearing wrong dimensions

ios,swift,sprite-kit,skshapenode

This is because your scene is being scaled. To fix the issue change your scene scale mode (in the GameViewController) to scene.scaleMode = .ResizeFill To see why this is, I recommend you read my answer here...

Can you apply delta time to an SKAction

swift,sprite-kit

You cannot do much about your FPS slowing down as you add more nodes to your view. Which device is running your app also determines your FPS. Newer models have a much faster CPU. To use delta time you can do something like this: -(void)update:(NSTimeInterval) currentTime { NSTimeInterval delta =...

SpriteKit: I'd need something like .pauseActionForKey()?

swift,sprite-kit,skaction

One way to solve this will be to create an empty SKNode and assign those action to that node which you want to be paused. This is so that when you pause the actions, it does not pause your whole game since you are assigning the SKActions to the scene...

how to transition scenes with swift in spritekit

swift,sprite-kit

You can use this code : 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) if self.nodeAtPoint(location) == self.playButton { let reveal = SKTransition.flipHorizontalWithDuration(0.5) let letsPlay = playScene(size: self.size) self.view?.presentScene(letsPlay, transition: reveal) }...

How to get a child sprite position in the view

swift,sprite-kit,skspritenode,sknode

You're nearly there, what you need to use is: let positionInScene = self.convertPoint(child.position, fromNode: platformGroupNode) // self in this case is your SKScene, you don't need self here but, IMO, it // makes it easier to understand what's converting what. Or an equivalent would be: let positionInScene = platformGroupNode.convertPoint(child.position, toNode:...

Swift sprite kit activity indicator

ios,swift,sprite-kit

Try like this let activityInd = UIActivityIndicatorView() activityInd.center = CGPointMake(view.bounds.midX, view.bounds.midY) activityInd.startAnimating() scene!.view?.addSubview(activityInd) ...

CPU & Memory steadily increase & FPS drops all because of vector movement

ios,objective-c,sprite-kit

I have figured out my own problem. During character movement through touch, the SKScene's -(void)update:(NSTimeInterval)currentTime method runs that characters class method [_player GPS:currentTime]; which tracks speed and distance. Here's the hiccup, that method sets the character texture according to the direction he is facing. Every frame the same texture continues...

TextField does not work

swift,sprite-kit

Your var TextField is local to the method didMoveToView so cannot be accessed from inside touchesBegan. Move this var outside of didMoveToView into the class level. Also, by convention vars should start with a lower case letter: textField rather than TextField....

How to make an SKNode continue in the same direction after finishing following a path

objective-c,sprite-kit

I suggest storing your node's CGVector (dx, dy) which represents the direction of movement for your node. For example, if the last moving vector was 15,15 that translates to your node having moved up and to the right. You can use this value to continue moving. If the values are...

Could not cast value of type 'UIView' (0x112484eb0) to 'SKView' (0x111646718)

ios,swift,sprite-kit,xcode7,xcode6.3.2

I finally fixed it! Instead of putting the functions in the GameViewController and calling them from game scene, I had to put the functions in gameScene and replace view with self.view!.

Randomizing node movement duration

swift,sprite-kit,skspritenode,skaction

When you run actions like from your example and randomize duration parameter with something like arc4Random this is actually happening: Random duration is set and stored in action. Then action is reused in a sequence with a given duration. Because the action is reused as it is, duration parameter remains...

Swift multiple level scenes

ios,swift,sprite-kit

You can override functions of baseScene in level1Scene, you just need to make sure you call the super version of the method. Here are a few examples, in your level1Scene class: override func didMoveToView(view: SKView) { super.didMoveToView(view) // Calls `didMoveToView` of `baseScene`. // Additional setup needed for `level1Scene`... } override...

Getting child SKSpriteNode Position

swift,sprite-kit

You can use the intersectsNode method on SKScene to check whether the child nodes are visible; intersectsNode will return true whilst the children are visible. for child in platformGroupNode.children { if let sprite = child as? SKSpriteNode where !intersectsNode(sprite) { child.removeFromParent() // Generate new platform... } } An alternative to...

Swift 1.2 - Setting element in array of optional types to nil— not allowed when passed in?

ios,swift,null,sprite-kit

Your problem is that board in the latter case is a let and can not be changed. Again the Swift error message is misleading here. If you want it to be an inout parameter then add this like (inout board:... but then you need to pass the parameter by reference...

Swift SpriteKit edgeLoopFromRect Issue

ios,swift,sprite-kit,cgrect,skphysicsbody

You are probably on the right track about .sks file. When scene is loaded from the .sks file the default size is 1024x768. Now you can dynamically set that based on the view size. So, swap your viewDidLoad with viewWillLayoutSubviews like this: override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let scene...

Orientation of screen?

ios,iphone,swift,sprite-kit

You have to allow all orientations in the project settings, then only orientations allowed are Portrait or Upside down portrait in your viewController except the GameViewController: // BaseViewController override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return UIInterfaceOrientationMask.Portrait.rawValue | UIInterfaceOrientationMask.PortraitUpsideDown.rawValue } else { return .All } }...

Binary operator '-=' cannot be applied to operends of type 'CGFloat' and 'Int'

ios,swift,sprite-kit

Luckily, the compiler is telling you exactly what the problem is here, the compiler isn't letting you mix types. The problem is here: var manSpeed = 10 That is implicitly creating manSpeed as an Int. So when you try to -= it with a CGFloat (which is what man.position.x is)...

Create linear motion with Swift in iOS [closed]

ios,swift,sprite-kit

You can create the host node – world: SKNode to control all the moving objects – just add them as childs. And use that node to rule the world – set world.speed = 0.0 to stop all SKActions, world.speed = 2.0 to move them twice as faster

Swift error: “double is not convertible to UInt8”

ios,swift,sprite-kit

zRotation is a CGFloat. Your dValue is a Double. They are not compatible. To multiply them, they must be same type: either both CGFloat or both Double. In this case, clearly CGFloat is desirable, since we will be assigning the result to a CGFloat. Declare your dValue as a CGFloat,...

Add SKShapeNode in another one

swift,sprite-kit,skshapenode

You should use SKSpriteNode instead. That way you can add it easily and without setting the position manually. Because in an SKSpriteNode, the center is always the center of the node: var tileBackground = SKSpriteNode(color: UIColor.whiteColor(), size: CGSizeMake(width: screenWidth, height: screenWidth)) tileBackground.name = "tileBackground" tileBackground.position = CGPoint(x: frame.midX, y: frame.midY);...

Dragging and flicking/throwing skspritenode [duplicate]

ios,swift,sprite-kit

This should work, I just dug it out from an old project. CGFloat dt is for changing the speed/power of the movement. var touching = false override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = touches.first as! UITouch let location = touch.locationInNode(self) if sprite.frame.contains(location) { touchPoint = location...

IOS SpriteKit Colision Detection: Resetting Position of an Object

objective-c,sprite-kit,collision-detection

You should take a look at run loop. Nothing is drawn before physics simulation is done. So I guess that changing position like you are doing is overwritten by physics simulation. This is the order of run loop: update is called scene evaluate actions didEvaluateActions is called physics simulation goes...

Resetting and changing speed on SKActions

swift,sprite-kit,velocity,skaction

Since velocity = distance / time, decreasing the duration will increase the speed the the sprite will move across the screen. Regarding your second point, by considering how SKAction.moveByX(300, y:0, duration: 1.0) moves the node to the right; SKAction.moveByX(-300, y:0, duration: 1.0) must therefore move the node to the left,...

Sprite Kit iOS Game development [closed]

ios,objective-c,image,animation,sprite-kit

To give you an idea of what I was talking about in my above comment, this is a tile disintegration animation I made of a 2D platform tile. It has 10 frames. The image work was done in Adobe Fireworks. ...

How to move a node from the different locations?

swift,sprite-kit

I am not using Swift at all, but this simple example should explain how to move sprite from one side to the other side of a screen and make all looks endless: import SpriteKit class GameScene: SKScene { let tree = SKSpriteNode(color: SKColor .greenColor(), size: CGSizeMake(20,30)) override func didMoveToView(view: SKView)...

What am i doing wrong when I switch scenes?

swift,sprite-kit

From what I can see, when there's a collision with person, you're removing nodes from the view, so they're still going to be gone when you recall GameScene from the restart() function in the EndScene. What you can do is create a func initialScene() in GameScene where you create everything...

Sprite Kit stop playing music file and start from the beginning

ios,objective-c,sprite-kit

To play background music in all scenes I will recommend AVAudioPlayer. You can write the code somewhere in your AppDelegate to access from all the scenes. Here is a sample code to achieve this using AVAudioPlayer // AVAudioPlayer *bgMusicLoop; - (void)playBackroundMusic:(NSString *)fileName withExtenstion:(NSString *)fileExtension { NSString *filePath = [[NSBundle mainBundle]...

need assistance in Collision between two objects

ios,swift,sprite-kit,collision-detection

try this func didBeginContact(contact: SKPhysicsContact) { let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask if collision == PhysicsCategory.Ball | PhysicsCategory.whiteBall { score++ scoreLabel.text = "Score: \(score)" } } ...

How can I stop the timer?

ios,swift,timer,sprite-kit

Not a 100% sure what if I understand your question. But if "timer" is referring to your looping action, you could do this: // This is just running your action with a name "scoreAction" let loopAction = SKAction.repeatActionForever( SKAction.sequence([actionrun,actionwait])) ScoreLabel.runAction(loopAction, withKey: "scoreAction") Later somewhere in you code you can stop...

Best way to convert SKShapeNode to SKSpriteNode [duplicate]

ios,swift,sprite-kit

The best solution is to design all of your assets (for various screen sizes) in a graphics editor (such as Photoshop or Illustrator) then create SKSpriteNodes using those assets. But if for some reason you really want to create your SKSpriteNodes using SKShapeNodes then the only way to do that...

Swift: Remove ads different scene in Spritekit

ios,swift,sprite-kit,mopub

This might not be the best way to do this, but it is probably the simplest. You could use an NSNotification to broadcast a message to your ViewController whenever you wish to show or hide you banner. For instance if you add an "observer" in your ViewController on init or...

SpriteKit: Physics bodies breaking under too much force (applyForce)

ios,sprite-kit,skspritenode

The higher the nodes with physics bodies, the lower the framerate. The lower the framerate, the crazier the engine gets. One time I've even see it make some kind of blackhole. It'll help if you lessen the force against the wall, whether gravity, or velocity from applyforce. Also making sure...

Creating a boundary around a tiled map

ios,swift,sprite-kit

After messing around with a bit of my code I found a fix was to just add the physicsBody to my map instead of the scene. A rather easy fix, so I'm surprised I didn't think of it sooner. With this in mind, I've answered my own question and no...

SKAction repeatActionForever not spawning entity

objective-c,sprite-kit,performselector,spawning

Try this: [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[ [SKAction waitForDuration:0.1], [SKAction performSelector:@selector(spawnBalloon) onTarget:self] ]]]]; ...

Changing from NSUserDefaults to NSCoding

ios,swift,sprite-kit,nsuserdefaults,nscoding

The class you want to save has to conform to the NSCoding protocol and implement required init(coder aDecoder: NSCoder) and func encodeWithCoder(aCoder: NSCoder). Here's a simplified example: class GameState: NSObject, NSCoding { var score: Int? var gameOver: Bool? init(score: Int, gameOver: Bool) { super.init() self.score = score self.gameOver = gameOver...

SpriteKit - Detect if sprite still moving/stopped

ios,sprite-kit

You can check physics body velocity vector to see if the node is moving in any direction. With something like this you would be probably fine : if((yournode.physicsBody.velocity.dx == 0.0f) && (yournode.physicsBody.velocity.dy == 0.0f)) { //do your stuff } Also there is a property on node's physics body called resting...

Why is my rectangle being drawn wrong?

ios,swift,graphics,sprite-kit

You are creating your border as a node within the scene but then setting its coordinates according to the view that is presenting the scene. The SKScene's coordinate system is not generally the same as the view presenting it so that is why the shape is different to what you...

How do I give the basket its exact shape, for a physics body, it is an image?

swift,sprite-kit,game-physics,skphysicsbody

You could use init(texture:size:) to create an SKPhysicsBody that matches the texture used by the basket. Here's an example: let basket = SKSpriteNode(imageNamed: "basket") basket.physicsBody = SKPhysicsBody(texture: basket.texture!, size: basket.size) // Do the rest of the setup. In the example above I'm force unwrapping the basket's texture property because I...

Collision Detection with an NSMutable array of Objects

sprite-kit,nsmutablearray,collision-detection

There are a couple of suggestions I have. As you are creating multiple instances of crab and adding them into the crabs array, I suggest you give each crab a unique name property. Your can do this by having a running int counter. For example: @implementation GameScene { int nextObjectID;...

Wrong node removed when using removeFromParent in spritekit

sprite-kit

You need a way to make each instance unique. One way to do this is to assign a unique name to each node instance. First you need to create a counter: @property (nonatomic) int myCounter; Then you use the counter as part of a node's name: myCounter++; myNode.name = [NSString...

Swift Sprite Kit recreating SKSpriteNode`s

ios,swift,sprite-kit

The answer is yes: Reuse game objects if possible. Each time you instantiate an object will incur some overhead. Avoiding that will always be better. For instance, you could just set the Platform.position to the top of the screen whenever you go out of the bottom bounds of the screen....

Swift iOS Sprite Kit - Fade sprite from one color to another [closed]

ios,swift,sprite-kit

You can use the colorizeWithColor method on SKAction to create an SKAction that will change the colour of an SKSpriteNode. Here's an example: let node = SKSpriteNode(color: UIColor.greenColor(), size: CGSize(width: 50, height: 50)) // Position and add the node to the scene... let colorize = SKAction.colorizeWithColor(UIColor.redColor(), colorBlendFactor: 1.0, duration: 5.0)...

Having blur at the edges of the image in SpriteKit game

image,sprite-kit

I can produce the same result if I use 300x150px logo.png. So,what you should do is to use appropriate assets, which is @2x (and @3x if you support iPhone 6+). When you use this naming conventions, iOS will choose right assets for you. This works with @1x and @2x, and...

SpriteKit collision angle of line and circle is odd

ios,sprite-kit,skphysicsbody

The ball gets reflected symmetrically to its angle of approach assuming it's a completely elastic collision. That means, to get the behavior you are looking for, the ball would need to approach exactly from one line mid-point to the next without any loss of energy. Sprite Kit's physics engine will...

iPhone 5s SpriteKit drawing oddities

ios,sprite-kit,skscene,skview

Anyways here is how I got good results: Just open up a new project and try this: In your GameViewContrller instead of using viewDidLoad use viewWillLayoutSubviews. EDIT: Here is a good explanation by Rob Mayoff about methods like viewDidLoad and viewWillLayoutSubviews. - (void)viewWillLayoutSubviews { [super viewWillLayoutSubviews]; // Configure the view....

Is it wise to export a Tiled layer into 1 big png file to save memory?

ios,objective-c,sprite-kit,tiled

You are most definitely better off having a single PNG/node as your background. There are some benefits of doing this: You have just one node. You can add the node to self and place it behind the rest of the action. This way it will always be there regardless of...

How do you apply one action to multiple Sprites in SpriteKit?

swift,sprite-kit,action

Contrary to sangony, I would have thought this is very possible, though I may be missing something. Could you not create a reference to an SKAction that is a sequence of move to X=0 and move to X=size.width? and repeat if forever. I'm not near my mac so I cant...

Swift SpriteKit iOS - Collisions: didBeginContact for one sprite, and not for others

ios,swift,sprite-kit

All you should do is add a condition in your didBeginContact() method, in your case, you should add the following to check: func didBeginContact(contact: SKPhysicsContact) { let other = contact.bodyA.categoryBitMask == ColliderType.Player.rawValue ? contact.bodyB : contact.bodyA switch other.categoryBitMask { case ColliderType.ScreenBoundary.rawValue: println("Hit Screen!") case ColliderType.Wall.rawValue: println("Hit Wall!") default: break }...

Sprite-Kit: SKAction.moveTo not working at all

ios,swift,sprite-kit,skaction

On each touch you create a new sprite and only in case 3 you add it to the node without running the move action. When reaching case 4 you just run the action on the new sprite instance without adding it to the node so it will never be shown....

Check if node is visible on the screen

ios,swift,sprite-kit

Using a worldNode which includes a playerNode and having the camera center on this node, you can check on/off with this code: float left = player.position.x - 700; float right = player.position.x + 700; float up = player.position.y + 450; float down = player.position.y - 450; if((object.position.x > left) &&...

Stopping the countUp speed rate

swift,sprite-kit

I guess that's happening because you are running same block over and over again after every touch. To ensure you run block only once, you can use some Bool indicator and after the first run, set its value appropriately, like this: if(!self.locked){ self.locked = true // at start, this value...

Swift - Adding background image behind a Sprite Kit Scene in View Controller

ios,swift,uiviewcontroller,sprite-kit

What you're describing can't be done with UIKit because your view can't be visible behind the SKView which renders your scene. In iOS 8+ you can use the SKView's allowsTransparency property. Documentation states: This property tells the drawing system as to how it should treat the view. If set...

What does @“//” do in childWithName and when to use it

ios,nsstring,sprite-kit,sknode

It doesn't do special things for all NSStrings, just strings used to search the node tree, for which it recursively searches all of self's children. From the documentation: When placed at the start of the search string, this [//] specifies that the search should begin at the root node and...

SKAction runAction does not execute completion block

swift,sprite-kit

From the SKAction Reference: An SKAction object is an action that is executed by a node in the scene (SKScene)...When the scene processes its nodes, actions associated with those nodes are evaluated. In other words, the actions for a node is run if and only if that node is in...

Spawn nodes at random times combing waitForDuration:withRange and runBlock: in an SKAction sequence

swift,sprite-kit,skspritenode,spawn,skaction

If I remember well, the waitForDuration:withRange: method works like so : if you put a duration of 3 (seconds) and a range of 1 seconds the random value that you get will be between 2 and 4 seconds. That said, you should use those value for what you described :...

How to check if two CGVectors are equal in Objective-C?

objective-c,sprite-kit

if( (vector1.dx == vector2.dx)&&(vector1.dy == vector2.dy) ) but be careful when comparing floats, because the comparison may be false because of rounding errors, so you may want to check to see if the differance of each component is very close to zero instead. if( (abs(vector1.dx - vector2.dx) < verysmallnumber) &&...

Random position func

ios,swift,sprite-kit

You should use arc4random_uniform method as follow: var randomPostion = CGPoint(x:CGFloat(arc4random_uniform(UInt32(self.view!.bounds.width))), y:CGFloat(arc4random_uniform(UInt32(self.view!.bounds.height)))) dvere1.position = randomPosition ...

Sprite Kit: can not see existing node's children

swift,sprite-kit,nodes

You are forgetting that the coordinate system of a node's child is different than that of the parent. Your parent node's "worldNode" position might be at x:500, y:500 and adding a child 20 points on top of the parent is going to x:0 y:20. You are adding the child by...

Swift Sprite Kit Camera Movement

ios,swift,camera,sprite-kit

Instead of directly declaring the position in centeronnode, use SKAction moveTo. It has a duration value. Replace your old centerOnNode func with: func centerOnNode(node: SKNode) { let cameraPositionInScene: CGPoint = node.scene!.convertPoint(node.position, fromNode: World) node.parent!..runAction(SKAction.moveTo(CGPoint(x:node.parent!.position.x - cameraPositionInScene.x, y:node.parent!.position.y - cameraPositionInScene.y), duration: 1)) } That should work, but I have't tested it...

Better character movement according to touch location

objective-c,ios8,sprite-kit

Your problem is you need to pick just 1 direction in which to move. Find out which way to move like below. NS_ENUM(unsigned short, MovementDirection) { Left = 0, Right = 1, Top = 2, Bottom = 3 } -(MovementDirection)movementDirectionBetweenCurrentPoint:(CGPoint)currentPoint newPoint:(CGPoint)newPoint { double dx = newPoint.x - currentPoint.x; double dy...

Set SKTexture for SKSpriteNode with a given sprite.name

objective-c,sprite-kit

Turns out I needed to use the childNodeWithName instead of trying to force a conditional on the .name property SKSpriteNode *card = (SKSpriteNode*)[self childNodeWithName:@"node0"]; [card setTexture:[SKTexture textureWithImageNamed:@"aTexture"]]; Not sure if this is a helpful question, mods feel free to erase if needed. ...

SpriteKit SKCropNode Masks everything

objective-c,ios8,sprite-kit,mask,skcropnode

I am guessing that the image as shown below is your designated background. Have you checked your nodes zPosition? If you want to show your spaceship infront of your background, you will have to adjust the zPosition to be higher than that of the background sprite....

Program crashes when function called multiple times

ios,swift,sprite-kit,skspritenode

It's really a bad idea to use animation by calling methods that way. Here is a way to do the same thing with sequenced and repeated actions wrapping the basic commands: let move = SKAction.moveTo(CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)), duration: 0) let fire = SKAction.moveTo(CGPointMake(100.0, 100.0), duration: 0.25) let wait = SKAction.waitForDuration(0.5) let...

Sequence Action With EnumerateChildNodeWithName

swift,sprite-kit,nodes,fade,alpha

The solution to this would be to make use of SKAction Sequences, it only runs the second action once the first action is completed. From the Apple Documentation A sequence is a set of actions that run consecutively. When a node runs a sequence, the actions are triggered in consecutive...

Not allowed to use property observer

swift,properties,sprite-kit

To make sure the sprites have the same position, set the position after physics and SKActions have been simulated. Do this in the didFinishUpdate() method of SKScene: override func didFinishUpdate() { sprite1.position = sprite2.position } ...

Presenting a SKSpritenode from different class (“addChild”)

ios,sprite-kit

Your mainNode is nil in your Keys because you never set it before you call initKeys. This in theory will get it working. Keys * KeysOBJ =[[Keys alloc] init]; KeysOBJ.mainNode = mainNode; [KeysOBJ initKeys]; Also consider this key1.position = CGPointMake((self.frame.size.width)- (self.frame.size.width)+350, (self.frame.size.height)-(self.frame.size.height)+50); self doesn't have a size because you just...

passing info from collectionView to gameScene

uiviewcontroller,sprite-kit,uicollectionview

Couple of ways to do this. One of them is using NSUserDefaults. To store data in NSUserDefaults, do this: // object can be almost anything. Strings, arrays, dictionaries... NSString *object = @"WellDone"; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:object forKey:@"Hamburger"]; [defaults synchronize]; To read NSUserDefaults, do this: NSString *myString =...