objective-ccocos3d

Cocos3D: Invoke delegate method from CC3Scene


In Cocos3D, how do invoke a callback from custom CC3Scene onto the UIViewController?

I'm following the CC3DemoMultiScene-iOS demo and here's what I've done.

Files of interest: CustomCC3Layer.h, CustomCC3Scene.h, MainViewController.m, MainViewController.h

CustomCC3Layer.h: There's nothing special in this file.

CustomCC3Scene.h: I declared the delegate...

@class CustomCC3Scene;

@protocol CustomCC3SceneDelegate <NSObject>

@optional
-(void)sceneCallbackMethod:(CustomCC3Scene *)scene didSelectPart:(NSString*)part;

@end

@interface CustomCC3Scene : CC3Scene {

@property (nonatomic, weak) IBOutlet id< CustomCC3SceneDelegate > delegate;

@end

MainViewController.h: Inherit CustomCC3SceneDelegate

@interface MainViewController : UIViewController<CustomCC3SceneDelegate>
...
@end

MainViewController.m: I created 3D scene and added as child of UIView.

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.view addSubview:[self createGLView]];
    CC3Backgrounder.sharedBackgrounder.shouldRunTasksOnRequestingThread = YES;
}

-(CCGLView*) createGLView {

    CGRect rect = CGRectMake(0, 0, 200, 300);

    CCGLView* glView = [CCGLView viewWithFrame: rect
                                   pixelFormat: kEAGLColorFormatRGBA8
                                   depthFormat: GL_DEPTH24_STENCIL8
                            preserveBackbuffer: NO
                               numberOfSamples: 1];

    CCDirector* director = CCDirector.sharedDirector;
    director.animationInterval = (1.0f / kAnimationFrameRate);
    director.displayStats = NO;
    director.view = glView;

    // Run the initial static 2D intro scene
    CCScene* scene = [[CustomCC3Layer layer] asCCScene];
    [director runWithScene:scene];

    // I need to set the delegate... but this throws unrecognized selector error
    // CustomCC3Scene* xxx = (CustomCC3Scene*)[[CustomCC3Layer layer] asCCScene];
    // xxx.delegate = self;

    return glView;
}

What I'm trying to do inside MainViewController.m is to set the CustomCC3SceneDelegate=self but this throws error. How do I properly set the delegate so that sceneCallbackMethod:didSelectPart: is called?


Solution

  • Solved my problem with the following code:

    -(CCGLView*) createGLView {
        ...
        ...
        CC3Layer* layer = [CustomCC3Layer layer];
        CustomCC3Scene* scene = (CustomCC3Scene*)[layer cc3Scene];
        scene.delegate = self;
        [director runWithScene:[layer asCCScene]];
    
        ...
    
    }