问题
I'm trying to retrieve the current position of the layer added as a child in a scene while a scene transition is occurring. The transition is an edited Cocos2D transition that slides the layer off the screen while a new one appears. I created my own implementation inside CCActionEase with an update method:
#import "JoinedMapsScene.h"
#import "JoinedMapsLayer.h"
@implementation CCEaseInWithPercentMult
-(void) update: (ccTime) t
{
[other update: powf(t,rate)];
CCScene * scene = [[CCDirector sharedDirector] runningScene];
CCNode* layer = [scene getChildByTag:0];
NSLog(@"% .2f",layer.position.x); //returns 0
NSLog(@"% .2f",layer.position.y); //returns 0
}
However these return 0 when the transition occurs. Presumably because I'm getting the position relative to itself?
EDIT:
I found out this will not work. I've correctly accessed my current scene by pointing to the right class by doing this:
JoinedMapsScene * scene = (JoinedMapsScene *)[[CCDirector sharedDirector] runningScene];
And calling my supposed method by doing this:
[scene getJoinedMapsLayerPosition];
To my surprise, while the transition is happening, the current runningScene is my transition class!
It gives my this exception: -[ExitLTransition getJoinedMapsLayerPosition]: unrecognized selector sent to instance 0x5e4e20
I need to figure out an alternate way of doing this.
回答1:
Add this in AppDelegate.h :
@class CCLayer;
@interface AppController : NSObject <UIApplicationDelegate, CCDirectorDelegate,UIGestureRecognizerDelegate>
{
CCLayer *mCurrentLayer;
}
@property (nonatomic, retain) CCLayer *currentLayer;
Add this in AppDelegate.mm :
@implementation AppController
@synthesize currentLayer = mCurrentLayer;
In your Layer init class use this. In all scene method.
@implementation MyMainMenu
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
MyMainMenu *layer = [MyMainMenu node];
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
app.currentLayer = layer;
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
You can check anywhere in project..
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
if([app.currentLayer isKindOfClass:[MyMainMenu class]])
{
MyMainMenu *mm = (MyMainMenu*) app.currentLayer;
[mm calFunction];
}
来源:https://stackoverflow.com/questions/12754390/cocos2d-get-layers-position-in-scene-from-another-class