2

My SKScene uses the following code to add sprites to the screen at certain time intervals, but if there is already a sprite on the screen when the next one is added my application freezes. Is there a way to add the same sprite to the screen without the application freezing?

let timer = SKAction.waitForDuration(1.00)
let addSpriteNode = SKAction.runBlock{
    self.addSprite()        
}

let sequence = SKAction.sequence([timer, addSpriteNode])
self.runAction(SKAction.repeatActionForever(sequence), withKey: "Sprites")
Rachel Evans
  • 120
  • 5

1 Answers1

6

Note: I am not currently at a computer that is capable of running Xcode, so I'm going off of memory.

Note 2: If I could comment, I would ask you to include the code located in the addSprite function. However, due to a lack of reputation, I am unable to do so. You could get a much faster and accurate answer by including that code, since that is the code that creates and adds the sprite.

Answer: You mention that you are attempting to add the same sprite to the screen - possibly like this:

let sprite = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(50,50))
func addSprite() {
    addChild(sprite)
}

You can not have the same sprite on the screen multiple times. Instead, each time you want a new sprite to be added to the screen, you have to create a new sprite. In your addSprite function, your code should create a new sprite, set it's properties, and then add it to the main view, as so:

fun addSprite() {
    let sprite = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(50,50)) // Creates a new sprite. You can customize this as needed.
    addChild(sprite) // Adds newly created sprite to screen.
}

I hope this helps. If you post your code, I could provide an answer more tuned to your question.

CodeIt
  • 769
  • 2
  • 7
  • 16
  • Yeah this works only problem i get now is using particles effects when collision is made with the sprite and removing it from screen, if i remove that sprite it removes all rather than that specific sprite. and getting the location of that sprite when it collides for the effect to take place. The effect is applied to all nodes on the screen except the collided sprite :( Sorry if i ask stupid questions, and thank you for responding to my question. – Rachel Evans Oct 28 '15 at 19:23
  • @Rachel Evans So your problem is it being removed from the screen, yes? I'm not incredibly fluent with SpriteKit, but it should be able for you to set each sprite a name which would act as a tag. You could then only remove sprites with that name. This depends on the program since it may be slow if you have many sprites on the screen. It's just an idea, and you'll have to make it custom since each program has it's own needs. Glad to help! And there are no stupid questions, just stupid mistakes! – CodeIt Oct 29 '15 at 18:48