Game Development Reference
In-Depth Information
3. Add the name of our background node, static NSString
*backgroundName = @"background"; to the Common.h ile so
we can reference it from anywhere.
4. Again, create a new file, an Objective-C class, name it ERGBackground ,
and set SKSpriteNode as its parent class when asked.
We will be handling everything background related in the ERGBackground
class. Let's make the class method return the preset background so we can use
it in our game.
Add this method to the implementation file and its prototype to the header file:
+ (ERGBackground *)generateNewBackground
{
ERGBackground *background = [[ERGBackground alloc]
initWithImageNamed:@"background.png"];
background.anchorPoint = CGPointMake(0, 0);
background.name = backgroundName;
background.position = CGPointMake(0, 0);
return background;
}
This method starts by creating a new background node from the file that we have
added before. We set the anchor point to (0,0) to help with scrolling. This way,
the position of the node will be at the left-bottom corner of the image so that we
don't have to calculate the starting position of the node. By default, the anchor point
is (0.5,0.5), and if we want to set two sprites back-to-back, we have to calculate halves
of those nodes. If we use (0,0) as the anchor point, we just add a new sprite on the
position where the last sprite ended and that's it.
Why did we assign static NSString as the name of the background and not just type
some arbitrary string? Compilers offer no error handling for the names of files or
names, so you can miss small mistakes in filenames, and this mistake won't be easy
to find. By using static NSString , we let compilers handle errors for us. Next is the
node position on screen—we want it to start from the left edge of screen, so we set
it there.
After we have created the background, we need to use it somewhere. In the
ERGMyScene.m file, import ERGBackground.h , and inside the header file, add the
@class ERGBackground line before the @interface declaration, and also add a
new property:
@property (strong, nonatomic) ERGBackground *currentBackground
 
Search WWH ::




Custom Search