我正在尝试从 Rod Strougo 和 Ray Wenderlich 的动手指南 Learning Cocos2D 中学习 Cocos2D,但它使用的是 Cocos 1,而不是现在已经推出的 2。我想这本书稍后仍然有意义,但在第一章中我遇到了一个问题,告诉导演运行一个场景,因为在 Cocos2D 2 中整个过程似乎已经不同了。
我宁愿不必买另一本书,所以我希望改变运行场景的方式相当简单。
这就是书中所说的:
找到-applicationDidFinishLaunching方法,注释掉:
[[CCDirector sharedDirector]runWithScene: [HelloWorld scene]];
并添加:
[[CCDirector sharedDirector]runWithScene:[GameScene node]];
我在 AppDelegate 中找不到任何类似的东西,相反看起来这与新方法有关:
[director_ pushScene: [IntroLayer scene]];
到目前为止,我尝试使教程中的内容适应新方法的尝试失败了,但也许这是一个简单的修复方法。
万一是过时的GameScene:
游戏场景.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "BackgroundLayer.h"
#import "GameplayLayer.h"
#import "CCScene.h"
@interface GameScene : CCScene
{
}
@end
GameScene.m
@implementation GameScene
-(id)init
{
self = [super init];
if (self != nil)
{
BackgroundLayer *backgroundLayer = [BackgroundLayer node];
[self addChild:backgroundLayer z:0];
GameplayLayer *gameplayLayer = [GameplayLayer node];
[self addChild:gameplayLayer z:5];
}
return self;
}
@end
最佳答案
您遇到的问题是类方法 +scene。在层内创建场景而不是初始化场景并让该实例创建自己的子层时使用它。当您更多地了解场景 -> 图层关系时,您将在本书的后面理解这些差异。
将-applicationDidFinishLaunching中的[director_pushScene: [IntroLayer scene]];
注释掉,替换成如下内容:
[director_ pushScene:[GameScene 节点]];
那应该能很好地满足您的需求。它将创建一个 GameScene 实例(CCScene 的子类),将您的两个 CCLayer 子类实例作为子实例,它们是您在 GameScene -init 方法中实例化的 backgroundLayer 和 gameplayLayer。
如果您好奇为什么调用 [GameScene scene]
对您不起作用,那是因为您从未在界面中声明过这样的方法。这有点令人困惑,但基本上您应该创建 CCLayer 的 Game Layer 子类,并在您的 .h 文件中声明此类方法:
+ (CCScene *)scene;
在您的实现 .m 文件中,您可以这样定义该方法:
// Class initializer method
+ (CCScene *)scene {
CCScene *scene = [CCScene node]; // Create a container scene instance
GameLayer *gameLayer = [GameLayer node]; // Create an instance of the current layer class
[scene addChild:gameLayer]; // Add new layer to container scene
return scene; // Return ready-made scene and layer in one
}
然后当您调用 [GameLayer scene]
时,+scene 方法会为该层创建场景并将其添加为子层。它更快,但根据我的经验,多层可能会更麻烦。
关于ios - 学习Cocos2D书籍过时附场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12824680/