本篇继续介绍另外一个在Cocos2dx中必经之路:在Cocos2dx中调用苹果Api以实现后期iOS的GameCenter和iap的相关操作, 那么这里就跟大家简单分享探讨下;如何在Xcode中进行c++与oc混编吧~
参考王哥说的 SimpleAudioEngine 类;
首先建立了两个类,一个object-c ,一个c++,详细如下:
HSpriteOC.h
#import <Foundation/Foundation.h>
NSString *str;
@interface HSpriteOC
+(void)testLog;
+(void)testLogWithStr:(NSString*)_str;
+(void)hMessageBox:(NSString*)pszMsg title:(NSString*) pszTitle;
@end
HSpriteOC.m
#import "HSpriteOC.h"
@implementation HSpriteOC
+(void) testLog
{
str = @"feng->string is:";
NSLog(@"HSprite:testLog");
}
+(void)testLogWithStr:(NSString *)_str
{
str = [NSString stringWithFormat:@"%@%@",str,_str];
NSLog(@"%@",str);
}
+(void)hMessageBox:(NSString *)pszMsg title:(NSString *)pszTitle
{
UIAlertView *messageBox = [[UIAlertView alloc]initWithTitle:pszTitle message:pszMsg delegate:nil cancelButtonTitle: @"OK" otherButtonTitles:nil];
[messageBox autorelease];
[messageBox show];
}
@end
这个类比较简单,简单定义了几个静态函数,打印和显示一个提示框,不赘述,大家大概看下就可以了;
下面来看c++的类:
HSpriteCPP.h
#ifndef __QQLogin__HSpriteCPP__
#define __QQLogin__HSpriteCPP__
#include "cocos2d.h"
using namespace cocos2d;
class HSpriteCPP:public cocos2d::CCSprite {
public:
static HSpriteCPP* hspriteWithFile(const char *spName);
void myInit();
virtual ~HSpriteCPP();
};
#endif /* defined(__QQLogin__HSpriteCPP__) */
HSpriteCPP.cpp
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "HSpriteOC.h"
#endif
#include "HSpriteCPP.h"
HSpriteCPP* HSpriteCPP::hspriteWithFile(const char *spName)
{
HSpriteCPP *pobSprite = new HSpriteCPP();
if (pobSprite && pobSprite->initWithFile(spName)) {
pobSprite->myInit();
pobSprite->autorelease();
return pobSprite;
}
CC_SAFE_DELETE(pobSprite);
return NULL;
}
void HSpriteCPP::myInit()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
//iOS代码
[HSpriteOC testLog];
[HSpriteOC testLogWithStr:@"wahaha"];
[HSpriteOC hMessageBox:@"cocos2dx调用oc函数" title:@"feng"];
#else
#endif
}
HSpriteCPP::~HSpriteCPP()
{
}
此类是个自定义精灵类,都是简单的创建等函数,其HSprite.cpp类的导入和在 myInit() 自定义初始化函数中都加入了预编译(#if #else #endif 对预编译不太了解的自定百度下吧),主要为了区别当前手机设备的平台区分做处理;而且在myInit()中我使用了object-c语法进行调用之前OC写的HSprite类函数;
其实通过观察以上两个类童鞋们估计很容易看出在xcode中cpp和oc如何混编;其实就是两点:
1. 混编的类需要将其实现类(.cpp)改成(.mm)类,那么Xcode就会智能知道这个类混编类了,不用复杂的操作;
2. 混编中cpp调用oc,其实就是各自使用各自语法即可,没差异!(最好对OC和c++都比较熟悉更效率)
然后在HelloWorldScene.cpp中加入以下测试代码:
HSpriteCPP *sp = HSpriteCPP::hspriteWithFile("Icon.png");
sp->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width*0.5,CCDirector::sharedDirector()->getWinSize().height*0.5-100));
this->addChild(sp,0);
别忘记导入对应使用的类哦~OK,看运行效果:
参考博客:http://www.himigame.com/iphone-cocos2dx/743.html