0

In an application I have, I initialise a SKSpriteNode (Ball) the didMoveToView method. I have a method that picks up on swipes up (That works fine, I tested it).

When that is called, it calls a method called [self jump]; In this method, I want it to run a few actions using the SKSpriteNode, Ball.

I used to know, but I have forgotten the code that allows you to access already initialised nodes. Say if I was going to write [Ball runAction:myAction]; , the compiler will replace 'Ball' with '_Ball'.

How can I manipulate the SKSpriteNode 'Ball' within another method? I don't think that I need to add any code but if it helps I will comply. Thank you in advance.

  • 2
    You need to store a reference to the ball sprite in an `@property` - then you can refer to it as `self.ball` - Don't use upper case letters for properties/variables - only for classes and don't use _ to access properties unless you know why you are doing it – Paulw11 Jan 31 '15 at 22:09
  • 1
    Create a class property http://stackoverflow.com/questions/695980/how-do-i-declare-class-level-properties-in-objective-c or an instance variable http://stackoverflow.com/questions/13263229/objective-c-instance-variables – sangony Jan 31 '15 at 22:09

2 Answers2

0

As suggested in the comments you could keep a pointer to the ball node, however another way could be to use the name property of SKNode.

When you instantiate the ball node assign the name property with a string identifier -

SKSpriteNode *ball = // create instance here
ball.name = @"TheBall";// set its name
[self addChild:ball];// add to scene and forget about it

Whenever you need to access it from within your SKScene subclass use -

SKSpriteNode *sameBall = (SKSpriteNode*)[self childNodeWithName:@"TheBall"];// don't forget the typecast

Now you can perform whatever actions you need to on the ball node.

An interesting read is the section on Searching The Node Tree found in the SKNode Class Reference by Apple.

Bamsworld
  • 5,670
  • 2
  • 32
  • 37
0

You can either create a class property for ball to access it everywhere.

 @property (nonatomic,strong) SKSpriteNode *ball

You can use self.ball to access the ball in every method.

self.ball = //SKSpriteNode initialize
[self addChild:self.ball]
// Add Child

SKNodes can also be searched by using the unique name of its children.

For example you can set

// Initialise
ball.name = @"Ball"
// Add Child

Then the SKScene can be searched using the function childWithName:

SKSpriteNode *ball = [self childNodeWithName:@"Ball"]

The first method is easier in your case.

rakeshbs
  • 24,392
  • 7
  • 73
  • 63
  • It comes up with a warning, that I am initialising a SKSpriteNode as an SKNode –  Feb 01 '15 at 07:01
  • 1
    It works now. I don't know how but the warning is gone ... thanks! –  Feb 01 '15 at 07:31