0

I am working on a project with 20 sprites and I am noticing a lot of code repetition. My sprites are named: sprite1, sprite2, sprite3.... so I am looking for a way to reference a sprite based on 2 variables. The first simply being "sprite" and the second being the integer, so I can change or loop through a range at any time. Is it possible to do something like this? Random example:

x = 1
while x <= 10 {
        sprite & x.physicsBody.affectedByGravity = true
        x++
}

instead of:

sprite1.physicsBody.affectedByGravity = true
sprite2.physicsBody.affectedByGravity = true
sprite3.physicsBody.affectedByGravity = true
sprite4.physicsBody.affectedByGravity = true
sprite5.physicsBody.affectedByGravity = true

so on...

3
  • 2
    It may be better to put them all in an array instead & loop through your desired indexes. Commented Jul 20, 2015 at 22:50
  • That could be a great solution. Could you show me an example? I wouldn't be sure how to reference an array or a portion of it when dealing with sprites. Commented Jul 20, 2015 at 22:52
  • There are different ways to organize that, you can group sprites with common attributes in different arrays... or as other comment suggests put them all together and access by index range though this is not very safe. Commented Jul 20, 2015 at 23:09

1 Answer 1

3

This could be as simple as:

for sprite in [sprite1, sprite2, sprite3, /* ... */] {
    sprite.physicsBody.affectedByGravity = true
}

However, having a bunch of local variables (or instance variables) like sprite1, sprite2, etc suggests that you're not making good use of your tools in some other way. What's meaningful about these sprites? Is there a way you can use the scene structure to better manage them?

For example, if all of the nodes you want to turn gravity on for are children of the same parent node, you could instead do something like:

for sprite in someContainerNode.children {
    sprite.physicsBody.affectedByGravity = true
}

Or, if there's some subset of nodes in your scene that you need to do this for, you could give them all the same name (say, in the SpriteKit Scene Editor in Xcode) and use that to find them:

scene.enumerateChildNodesWithName("needsGravity") { node, stop in
    node.physicsBody.affectedByGravity = true
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.