Reputation: 454
So I'm very new to SpriteKit and Swift, and I don't really understand the concept behind nodes (or really anything in sprite-kit for the matter). I'm requesting you explain the concept of nodes to me.
I'm much more used to having a different instance of a variable for each node (such as making an array), which allows me to very specifically reference any single node. However in sprite kit this doesn't seem to be the case since you simply just make it once and call multiple instances of it with addChild. (Way better than what I've been doing...)
This kinda boggles me because I mainly don't understand how I could test a scenario or something for these or reference one individually. For example, I'm trying to get an object to be removed from the scene with removeFromParent()
, but I don't how to implement something like:
if(enemy.position.x == 0)
{
SKAction.removeFromParent()
}
Before I would setup a for loop that checks every single enemy but this is SUPER inefficient. I think I would do this in the update method provided by the physics engine, but like I said I have no idea how to call it.
So my question is basically to have you explain to me the concept of what's going on here. Pretend I have absolutely no knowledge of this type of programming (which I pretty much don't) and if you could break it down to me like I'm five that would be great :D!
Thanks!
Upvotes: 2
Views: 111
Reputation: 7252
I had similar troubles when first learning SpriteKit, coming from working with UI* objects.
To get every node in a scene
self.children
OR you can pass //*
into enumerateChildNodesWithName:
To get a specific node you can reference it by name.
self.childNodeWithName("myNode")
To get a node at a touch location
Objective-C
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
SKSpriteNode *touchedNode = (SKSpriteNode *)[self nodeAtPoint:positionInScene];
}
Swift
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = (touch as UITouch).locationInNode(self)
if let touchedNode = self.nodeAtPoint(location) {
// Do something with node here.
}
}
}
I almost always give a name to my nodes as it makes them far easier to work with. It's also the only way you can really interact with them when designing your scenes in .sks files.
What helped me was looking at the button implementation on Apples DemoBots sample project.
Upvotes: 2