2012年2月 的存档

Android and IOS game engine

2012年2月29日 没有评论

I’m looking for a 2D game engine to use to target both Android and IOS without the need to rewrite my code. Bonus points if WP7 is supported too.

I found many of them, but they all uses c++. I would really like a game engine that uses an interpreted/high level language(c#, java, python, lua, you say. My preference is toward strong typed ones), productivity with this languages is far better than with C/C++(at least on my side)

I found this ones:

Emo framework


  • BSD licence
  • Uses interpreted language (Squirrel, ps: never heard of it, but it seams good)


  • Really simple Api
  • No access to full features of the underlying system (no way to connect with bluetooth or internet using the os api)



  • C#
  • WP7 support, + other
  • it seams very well supported


  • both mono for android and mono for ios are 400$ each. I’m a student and i develop in free time, i have no such money to invest, and if i must chose between the 2, i’ll chose android and stick with AndEngine, that is really good for my needs right now(too sad it is Android only)

Well, i don’t know other engines that work on both platforms and use an interpreted language.

About C++ ones,


  • open source
  • C++
  • well documented? (since it is a porting from cocos2d, i expect the tutorials for cocos2d to be useful to cocos2d-x too)
  • WP7 possible porting
  • it doesn’t ease developing for both platform from only pc (obviously a mac is needed in any case to load the app to the store)


Have i missed some good one? I really would like to find a good one that uses an interpreted language, but the one i found is too much expensive or doesn’t fulfil my needs(i need to fully access the networking apis). If such an engine doesn’t exists, i think i’ll use cocos2d-x (since it is open source), but i’m sure i haven’t taken into consideration other engines!

There are many game engines that work for both Android and iOS, 26 by my last count. Take a look at http://mobilegameengines.com/

There is also Unity.

For 2D games you don’t need the Pro version of it, though the non-Pro is still 2*$400 for iOS and Android.

It is well known and uses mono (C#) as the scripting engine.

You also have the option to compile mono for ARM/Android, and use it natively. It is not supported, and you have to create some wrappers around your code, so it can interface with the Android native APIs.

If using commands carefully you can then port this code with some changes to Mono for iOs and XNA (WP7) too

V-Play (v-play.net) is a cross platform 2D game engine based on Qt/QML. API reference.
It already supports iOS, Android, Symbian, MeeGo and Desktop platforms. BlackBerry and Windows Phone support is in progress and will be added soon.
V-Play also comes with ready-to-use game templates for the most successful game genres like tower defense, platform games or puzzle games, several tutorials and demos. (V-Play examples & demos)

(Disclaimer: I’m one of the guys behind V-Play)

I’d also suggest GameSalad, it’s 2D, runs on Android, iOS, and used HTML5 to support Tizen. It’s got a declarative drag-and-drop programming UI (so if you’re looking for traditional text based program it’s not for you). There are many examples and tutorials online and a couple of marketplaces of templates you can use as a starting point. Disclaimer, I’m one of the co-founders.

分类: stackoverflow精选, unity3d 标签:

Color Changing Sprites Cocos2d

2012年2月29日 没有评论

I need my sprite to transition to one color to another and on and on… like blue tint then green then purple, but i cannot find any good actions for that and am wondering, should i use animations? or is there an incorporated action for this?

you can use CCTintTo action to change the color of the sprite

[sprite runAction:[CCTintTo actionWithDuration:2 red:255 green:0 blue:0]];

since i saw several questions about replacing pixel colours in sprites, and i did’nt see any good solution (all solution only tint the color, and none of them is able to change an array of colours without forcing you into creating multiple image layers which construct the final image you want, i.e: one layer for pans, other for show, other for shirt, another for hair colour… and it goes on – note that they do have their advantages like the ability to use accurate gradients)

my solution allows you to change array of colors, meaning you can have a single image with a known colors (you dont want any gradiants in this layer, only colours that you KNOW their values – PS this only applies to colors you intent to change, other pixels can have any colour you want)
if you need gradiants over the colours you change, create an additional image with only the shading and place it as a child of the sprite.

also be aware that i am super-new to cocos2d/x (3 days), and that this code is written for cocos2dx but can be ported to cocos2d easily.

also note that i didnt test it on android only on iOS, i am not sure how capable is android official gcc and how will it deal with the way i allocate _srcC and _dstC, but again, this is easily portable.

so here it goes:

cocos2d::CCSprite * spriteWithReplacedColors( const char * imgfilename, cocos2d::ccColor3B * srcColors, cocos2d::ccColor3B * dstColors, int numColors )
    CCSprite *theSprite = NULL;

    CCImage *theImage = new CCImage;
    if( theImage->initWithImageFile( imgfilename ) )
        //make a color array which is easier to work with
        unsigned long _srcC [ numColors ];
        unsigned long _dstC [ numColors ];
        for( int c=0; c<numColors; c++ )
            _srcC[c] = (srcColors[c].r << 0) | (srcColors[c].g << 8) | (srcColors[0].b << 16);
            _dstC[c] = (dstColors[c].r << 0) | (dstColors[c].g << 8) | (dstColors[0].b << 16);

        unsigned char * rawData = theImage->getData();
        int width = theImage->getWidth();
        int height = theImage->getHeight();

        //replace the colors need replacing
        unsigned int * b = (unsigned int *) rawData;
        for( int pixel=0; pixel<width*height; pixel++ )
            register unsigned int p = *b;
            for( int c=0; c<numColors; c++ )
                if( (p&0x00FFFFFF) == _srcC[c] ) 
                    *b = (p&0xFF000000) | _dstC[c];

        CCTexture2D *theTexture = new CCTexture2D();
        if( theTexture->initWithData(rawData, kCCTexture2DPixelFormat_RGBA8888, width, height, CCSizeMake(width, height)) )
            theSprite = CCSprite::spriteWithTexture(theTexture);

    return theSprite;

to use it just do the following:

ccColor3B src[] = { ccc3( 255,255,255 ), ccc3( 0, 0, 255 ) };
ccColor3B dst[] = { ccc3( 77,255,77 ), ccc3( 255, 0 0 ) };
//will change all whites to greens, and all blues to reds. 
CCSprite * pSprite =  spriteWithReplacedColors( "character_template.png", src, dst, sizeof(src)/sizeof(src[0]) );

of course if you need speed, you would create an extension for a sprite that create a pixel shader that does it hw accelerated at render time ;)

btw: this solution might cause some artefacts on the edges on some cases, so you can create a large image and scale it down, letting GL minimise the artefact.
you can also create “fix” layers with black outlines to hide the artefacts and place it on top etc.
also make sure you don’t use these ‘key’ colors on the rest of the image you don’t want the pixels changed.
also keep in mind that the fact that the alpha channel is not changed, and that if you use basic images with pure red/green/blue colors only, you can also optimize this function to eliminate all artefacts on edges automatically (and avoid in many cases, the need for an additional shade layer) and other cool stuff (multiplexing several images into a single bitmap – remember palette animation?)

enjoy ;)

分类: cocos2d, stackoverflow精选 标签:


2012年2月26日 没有评论











移动终端网页游戏移植研发框架【人物角色模型介绍】移动终端网页游戏移植研发框架【人物角色模型介绍】View Code

findViewById(R.id.btnPlayerInfo).setOnClickListener(new OnClickListener() {
public void onClick(View v) {

Indicator.beginIndicator(TApp.getActivity(), "查询中", "正在查询,数据加载中...", R.drawable.icon);

thread_getuserinfo = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
if (pui.getGetUserInfoList() != null) {
try {
} catch (Exception e) {






移动终端网页游戏移植研发框架【人物角色模型介绍】移动终端网页游戏移植研发框架【人物角色模型介绍】View Code

 <TextView android:id="@+id/tvLevel" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="角色等级" />
<TextView android:id="@+id/tvPlayerName" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="角色姓名" />
<TextView android:id="@+id/tvPlayerChenHao" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="称号" />
<TextView android:id="@+id/tvPlayerJingXue" android:layout_width="wrap_content" android:layout_height="wrap_content"

<TextView android:id="@+id/tvExp" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="当前经验/生升级经验" />
<TextView android:id="@+id/tvPlayerAttack" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="攻击力" />
<TextView android:id="@+id/tvPlayerDefence" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="防御力" />
<TextView android:id="@+id/tvPlayerSkill" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="特殊技" />


移动终端网页游戏移植研发框架【人物角色模型介绍】移动终端网页游戏移植研发框架【人物角色模型介绍】View Code

String playlevel = playerinfo.getUserLevel();
setTextViewText(R.id.tvLevel, "等级:" + playlevel );
String nowexp = playerinfo.getExp();
String nextexp = playerinfo.getNextExp();
setTextViewText(R.id.tvExp, "经验:" + nowexp +"/"+ nextexp);








分类: 未分类 标签:


2012年2月25日 没有评论







       这个是最标准的多层架构了,在里面加入了一些工具,但最主要的还是和客户端通信用的接口了。 这就是我们的服务器端;










分类: 未分类 标签:


2012年2月25日 没有评论


    下面也就详细和大家分享一下我2012年的一些项目吧,由于我前几年一直都在游戏公司工作,并且做的是网页游戏。我对网页游戏的研发框架也有一定的了解,综合对手机移动终端的市场,我今年的项目也就是这个“游戏”。是一款在线页游的移动终端版本。这款页游题材是一款武侠类型的大型网页游戏【回合制】。项目的立项是在2011年11月份,目前项目已经完成了50%左右进度,如果大家了解,玩过网页游戏的可以知道现在的网页游戏,已经将2DRPG客户端移植到网页了。大部分的网页游戏都已经成熟化,并且泛滥。但是真正属于一款移动终端的网络游戏,是少之又少的,三国杀,QQ游戏这些比较成功,少数其他的都是通过客户端移植内嵌WEBview的形式展示,且不说移植的可靠性,和可玩性大大降低不说,单独界面就很让人讨厌和提的起兴趣,三国杀和QQ游戏的UI是非常成功的。所以,单独为移动终端研发的产品,才是我,我们要做的真正的事情,而并非移植!下面我单独将我的项目资料贴一点图给大家鉴赏吧,游戏项目叫做 “剑神客栈”,目前安卓版本项目进度已经完成了50%, IOS项目进度已经开始建模。至于具体的框架和模型稍后会和大家慢慢分享。这也是一个美妙的旅程,下面每周我的会抽时间来和大家分享我们的游戏,我们建了一个QQ群【45578308】,和大家一起讨论游戏研发,和游戏测试的群。如果对剑神客栈有兴趣的朋友可以加入进来和我们一起体验游戏。













分类: 未分类 标签:

How do I make water as seen in Sea Stars?

2012年2月14日 没有评论

There is a nice Sea Stars iOS application out there, with a good looking water effect can be seen on video.

I have found Tiny Wings “waves” tutorial on here, so I guess I can figure out how to make waves.

I wonder how do I make effect when hero pops out of the water (splash and water deformation). Also I wonder how do I make effect when I look on water line from above and from below – please notice how water line changes when hero is above it and below it.

I am familiar with Box2d and Cocos2d, so I wonder if this can be done within that knowledge. Also I wonder if Chipmunk can help.

It looks like the waves in sea stars aren’t really simulated, but just simple perlin noise and adding a simple bump when making a splash. If you want water simulation, I posted some code I wrote to do that here:

分类: stackoverflow精选, unity3d 标签:

Cocos2D project with many scenes does not release memory properly

2012年2月11日 没有评论

I’ve got a great problem and I don’t understand very well why occurs. This is the case:

  • Have a great project in Cocos2D with 10 scenes. Each scenes is a page of a book with huge sprites. It uses Kobold2D 1.0.2 implementation.
  • Every page has common objects in a singleton class, to put a common menus via LayerColor.
  • The sprites is TexturePacker in PVR.CCZ RGBA4444 and in iPad memory
    are around 16-20Mb every spritesheet loaded.
  • I use CCTransitionTurnPage for replaceScene for one to the next one.
  • At init method of each page (class), load the texture and FrameFile.
  • At onExit method of each page (class), unload the textures and frameFile. I used the dumpCachedTextureInfo and says me textures load and unload from memory perfectly.
  • Of course, I remove from child all objects. All my sprites are common variables declared on the interface section at .h, because I need to access them in every method of the class.
  • My project is made with Kobold2D integration in a ARC project (but you know the attached Kobold2D project has ARC not enabled for compatibility problem)

The fact is when I start the project, everything seems perfect but memory is increasing for every scenes (page) I made. Page1: 30Mb., Page2: 40, Page 3: 54, Page 4: 65… After 7 or 8 scenes, Instruments, Xcode or the iPad itself hangs the application without any message (except Instruments with a final Low memory Warning).

Why there’s no memory releasing after each scenes? Maybe it’s because ARC and the no super dealloc variable. Why textures appears unload perfectly but seems like there’s no unload because memory is growing without control until crash?

I was having a similar problem with memory retention and no leaks showing up in instruments. I couldn’t get -(void) dealloc to even get called until I wrote the following into every scene’s .m file:

-(void) onExit {
    //unschedule selectors to get dealloc to fire off
    [self unscheduleAllSelectors];
    //remove all textures to free up additional memory. Textures get retained even if the sprite gets released and it doesn't show as a leak. This was my big memory saver
    [[CCTextureCache sharedTextureCache] removeAllTextures];
    [super onExit];

After implementing this, my memory was released after every replaceScene: was called. Hope this is of some use to you.

After months of working, I learned the most important lesson on Cocos2D. The retain increase by one when you put any CCNode object on a CCArray or NSArray or NSDictionary… This means you must release the objects from this objects before the CCLayer or CCScene dealloc.

You must put a [array removeAllObjects] or [dictionary release] on the -(void)cleanup and after all your objects has removed, then put a [super cleanup];

In the meantime, on -(void)onExit you must remove all scheduler from the instance. Not only a scheduler itself. Remember to stopAllActions on any CCNode. But, carefully, because stoping actions from CCNodes (Sprites or something) must be on cleanup, before any removeAllObjects.

And remember: if CCLayer or CCScene does not remove properly, SimpleAudioEngine not will release the audio too.

Thanks in advance to all of you

分类: cocos2d, stackoverflow精选 标签:

How to rotate coordinate system?

2012年2月8日 没有评论

I am trying to find the new value of a coordinate if I rotate around the origin.

For example, say I have the point (1,1).
If I rotate the coordinate axis 45 degrees around the origin, the transformed coordinate would be (0,1.414)

Is there a way to do this efficiently in cocos2d, or in objective-c ?
Even answers explaining the math to do this would be helpful.

See this page:

This is the formula:

x’ = x cos f – y sin f

y’ = y cos f + x sin f

Remember that sin and cos takes radians, so you have to do like this:

double x,y;
double newX,newY;
double angle;

//Test values:
angle = 45;

double rad = angle*M_PI/180;

newX = x * cos(rad) - y * sin(rad);
newY = y * cos(rad) + x * sin(rad);

I didn’t test this, so there might be typos… ;)

分类: stackoverflow精选, unity3d 标签:

playing video on top of OpenGL view in android

2012年2月6日 没有评论

I’m developing a game using cocos2d-x and I want to play video in it.
The activity has one OpenGL view and I also put additional VideoView on top of it and set visibility to INVISIBLE.

When I need to play video, I just hide OpenGL view and enable my VideoView. After that I create MediaPlayer, call setDisplay with holder of that VideoView, etc. and eventually video plays well. When video finishes, I switch visibilities back again – opengl to VISIBLE and videoview to INVISIBLE.

However, the problem is that when I try to play video second time, it just doesn’t show up, however, sound from the video is being played.

Is there any catch with visibilities?

I just modified the ApiDemo to see whether it works. I have blog the full code here : post without using separate media player for video view we can set the video and play


   //I could add touch listener in onCreate

//touch event will go all the way down to GLSurfaceView
//Here i could chnage the video view position
public boolean onTouch(View view, MotionEvent motionEvent) {
    return true;

You will need a surfaceview to play video at using android MediaPlayer class.

To play video above GLSurfaceView, create an android Custom Dialog which contains a surfaceView and play video on that.

You can do this by adding dynamically video view on the surface of glview. First create a parent view (any layout) add video view in same parent view then add this parent view on the gl surface view. I have done this before and it was working for me. for your reference :

     // first set the content view as your glview with your params.
     setContentView(mGLView, gl_params);

     // add a parent view for video view. rl is relative layout
     addContentView(rl, rl_params);

     // now add the video view inside this parent view.
     rl.addview(video_view, video_view_params)
分类: stackoverflow精选, unity3d 标签:

Cocos2d – Initial app layer displays incorrectly on app load, displays appropriately after reload

2012年2月3日 没有评论

I’m using a GameManager singleton to handle some of the shared tasks required by my game. One of those tasks is loading individual game scenes. When the game starts up, whichever scene/layer combo I have displayed appears incorrectly; it looks like maybe the coordinates that items are positioned in relation to are wrong.

It doesn’t matter which layer I choose–they all appear incorrectly. If you click on a button and load another scene/layer, then go back to the scene/layer in question, everything displays correctly. This only happens on retina display devices, so I think it might be related to the scaling I set for the different display types in the game manager. However, changing the scaling for Retina displays breaks things even more (the layers are too small).

Here’s my AppDelegate.h

#import <UIKit/UIKit.h>

@class RootViewController;

@interface AppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow            *window;
    RootViewController  *viewController;

@property (nonatomic, retain) UIWindow *window;



#import "cocos2d.h"

#import "AppDelegate.h"
#import "GameConfig.h"
#import "RootViewController.h"
#import "GameplayScene.h"
#import "GameManager.h"

@implementation AppDelegate

@synthesize window;

- (void) removeStartupFlicker
#if GAME_AUTOROTATION == kGameAutorotationUIViewController

- (void) applicationDidFinishLaunching:(UIApplication*)application
    // Init the window
    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Try to use CADisplayLink director
    // if it fails (SDK < 3.1) use the default director
    if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
        [CCDirector setDirectorType:kCCDirectorTypeDefault];

    CCDirector *director = [CCDirector sharedDirector];

    // Init the View Controller
    viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
    viewController.wantsFullScreenLayout = YES;

    EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
                                   pixelFormat:kEAGLColorFormatRGB565   // kEAGLColorFormatRGBA8
                                   depthFormat:0                        // GL_DEPTH_COMPONENT16_OES

    // attach the openglView to the director
    [director setOpenGLView:glView];
    [director setDeviceOrientation:kCCDeviceOrientationPortrait];

    [director setAnimationInterval:1.0/60];
    [director setDisplayFPS:YES];

    // make the OpenGLView a child of the view controller
    [viewController setView:glView];

    // make the View Controller a child of the main window
    [window addSubview: viewController.view];

    [window makeKeyAndVisible];

    [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];

    // Removes the startup flicker
    [self removeStartupFlicker];

    // Run the intro Scene
    //[[CCDirector sharedDirector] runWithScene:[GameplayScene node]];
    [[GameManager sharedGameManager] runSceneWithID:kMainMenuScene];

- (void)dealloc {
    [[CCDirector sharedDirector] end];
    [window release];
    [super dealloc];


#import <Foundation/Foundation.h>
#import "Constants.h"
#import "CommonProtocols.h"

@interface GameManager : NSObject {
    BOOL isMusicON;
    BOOL isSoundEffectsON;
    BOOL hasPlayerDied;
    BOOL newHighScore;
    BOOL newBestTime;
    BOOL isUiTextLeft;
    int currentScore;
    int highScore;
    int lengthPlayed;
    int bestTime;
    int randomPurple;
    int randomGreen;
    int timeBonus;
    int timeTillDeath;
    int uiBackgroundHeight;
    CharacterStates previousPurpleState;
    CharacterStates previousGreenState;
    SceneTypes currentScene;

@property (readwrite) BOOL isMusicON;
@property (readwrite) BOOL isSoundEffectsON;
@property (readwrite) BOOL hasPlayerDied;
@property (readwrite) BOOL newHighScore;
@property (readwrite) BOOL newBestTime;
@property (readwrite) BOOL isUiTextLeft;
@property (readwrite) int currentScore;
@property (readwrite) int highScore;
@property (readwrite) int lengthPlayed;
@property (readwrite) int bestTime;
@property (readwrite) int randomPurple;
@property (readwrite) int randomGreen;
@property (readwrite) int uiBackgroundHeight;
@property (readwrite) CharacterStates previousPurpleState;
@property (readwrite) CharacterStates previousGreenState;
@property (readwrite) int timeBonus;
@property (readwrite) int timeTillDeath;

-(void)openSiteWithLinkType:(LinkTypes)linkTypeToOpen ;



#import "GameManager.h"
#import "GameplayScene.h"
#import "MainMenuScene.h"
#import "OptionsScene.h"
#import "CreditsScene.h"
#import "IntroScene.h"
#import "LevelCompleteScene.h"

@implementation GameManager

static GameManager* _sharedGameManager = nil; 
@synthesize isMusicON;
@synthesize isSoundEffectsON;
@synthesize hasPlayerDied;
@synthesize newHighScore;
@synthesize newBestTime;
@synthesize isUiTextLeft;
@synthesize currentScore;
@synthesize highScore;
@synthesize lengthPlayed;
@synthesize bestTime;
@synthesize previousPurpleState;
@synthesize previousGreenState;
@synthesize randomPurple;
@synthesize randomGreen;
@synthesize timeBonus;
@synthesize timeTillDeath;
@synthesize uiBackgroundHeight;

+(GameManager*)sharedGameManager {
    @synchronized([GameManager class])
            [[self alloc] init]; 
        return _sharedGameManager;
    return nil; 

+(id)alloc {
    @synchronized([GameManager class]){
        NSAssert(_sharedGameManager == nil, @"Attempted to allocate a second instance of the Game Manager singleton");
        _sharedGameManager = [super alloc];
        return _sharedGameManager;
    return nil;

-(id) init {
    self = [super init];
    if (self != nil) {
        // Game manager initialized
        CCLOG(@"Game manager singleton, init");
        hasPlayerDied = NO;
        NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [dirPaths objectAtIndex:0];

        NSMutableData *gameData;
        NSKeyedUnarchiver *decoder;

        NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:@"gameState.dat"];
        gameData = [NSData dataWithContentsOfFile:documentPath];

        if (gameData) {
            decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:gameData];

            highScore = [decoder decodeIntForKey:@"highScore"];
            bestTime = [decoder decodeIntForKey:@"bestTime"];
            isMusicON = [decoder decodeBoolForKey:@"isMusicON"];
            isSoundEffectsON = [decoder decodeBoolForKey:@"isSoundEffectsON"];
            isUiTextLeft = [decoder decodeBoolForKey:@"isUiTextLeft"];
            //currentScore = [decoder decodeIntForKey:@"currentScore"];

            [decoder release];
        } else {
            highScore = 0;
            bestTime = 0;
            isMusicON = TRUE;
            isSoundEffectsON = TRUE;
            isUiTextLeft = TRUE;
            //currentScore = 0;

        CCLOG(@"Music - %s", isMusicON ? "true" : "false");
        CCLOG(@"Sound - %s", isSoundEffectsON ? "true" : "false");
        currentScore = 0;
        timeBonus = 0;
        timeTillDeath = 0;
        uiBackgroundHeight = 0;
        currentScene = kNoSceneUninitialized;

    return self;

-(void)runSceneWithID:(SceneTypes)sceneID {

    SceneTypes oldScene = currentScene;
    currentScene = sceneID;
    id sceneToRun = nil;

    switch (sceneID) {
        case kMainMenuScene:
            sceneToRun = [MainMenuScene node];
        case kOptionsScene:
            sceneToRun = [OptionsScene node];
        case kCreditsScene:
            sceneToRun = [CreditsScene node];
        case kIntroScene:
            sceneToRun = [IntroScene node];
        case kLevelCompleteScene:
            sceneToRun = [LevelCompleteScene node];
        case kGameplayScene:
            sceneToRun = [GameplayScene node];
            CCLOG(@"Unknown ID, cannot switch scenes");

    if (sceneToRun == nil) {
        // Revert back, since no new scene was found
        currentScene = oldScene;

    // Menu Scenes have a value of < 100
    if (sceneID < 100) {

        if ([[CCDirector sharedDirector] enableRetinaDisplay:YES]) {
            // iPhone 4 Retina
            [sceneToRun setScaleX:1.0f];
            [sceneToRun setScaleY:1.0f];
            CCLOG(@"GM:Scaling for iPhone 4 (retina)");
        } else {
            [sceneToRun setScaleX:1.0f];
            [sceneToRun setScaleY:1.0f];
            CCLOG(@"GM:Scaling for iPhone 3G(non-retina)");

    if ([[CCDirector sharedDirector] runningScene] == nil) {
        [[CCDirector sharedDirector] runWithScene:sceneToRun];
    } else {
        [[CCDirector sharedDirector] replaceScene:sceneToRun];

You are calling node with the scene objects call [MainMenuScene scene];and try

and make this method with return type CCScene* and use to get return the scene and write

[[CCDirector sharedDirector]runWithScene:[obj runSceneWithID:1]];

Edit –

-(CCScene*)runSceneWithID:(SceneTypes)sceneID {

    SceneTypes oldScene = currentScene;
    currentScene = sceneID;
    id sceneToRun = nil;

    switch (sceneID) {
        case kMainMenuScene:
            sceneToRun = [MainMenuScene node];
        case kOptionsScene:
            sceneToRun = [OptionsScene node];
        case kCreditsScene:
            sceneToRun = [CreditsScene node];
        case kIntroScene:
            sceneToRun = [IntroScene node];
        case kLevelCompleteScene:
            sceneToRun = [LevelCompleteScene node];
        case kGameplayScene:
            sceneToRun = [GameplayScene node];
            CCLOG(@"Unknown ID, cannot switch scenes");
            return nil;

    if (sceneToRun == nil) {
        // Revert back, since no new scene was found
        currentScene = oldScene;

    return sceneToRun;

I ran into a similar problem once, but I can’t seem to relate it directly to your code.

In short, the issue is that while I am building my layer/scene in the init method, the nodeToWorldTransformation (at least, possibly others as well) is not set. So, if you are trying to calculate the world coordinates (or possibly the size in world coordinates) of something, it does not work.

Now, in may case, I used that transform to calculate a scale factor at init time, and it was wrong. If I delayed the calculation to after the transformation was set, then everything was ok. The transformation becomes ready only after the layer you are creating has been added to its parent, but I am not exactly sure when it does. Finally, in my case I simply hardcoded the transformation, knowing all dimensions at init time.

It seems that your case could be analogous to this, but, as I said, I cannot relate this to your code.

分类: cocos2d, stackoverflow精选 标签: