<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> </span><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">学习cocos2dx,都说源代码是最好的文档,看看源代码,可以了解cocos2dx当中事件是如何处理的,对于整个引擎有更深入的理解。</span>
1.如何接收iOS事件
2.自己进行封装,然后分发下去的。
如何接受iOS事件
主要相关文件,AppController.mm。主要相关类:CCEAGLView.
主要代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
cocos2d::Application *app = cocos2d::Application::getInstance();
app->initGLContextAttrs();
cocos2d::GLViewImpl::convertAttrs();
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds]
pixelFormat: (NSString*)cocos2d::GLViewImpl::_pixelFormat
depthFormat: cocos2d::GLViewImpl::_depthFormat
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0];
// Use RootViewController manage CCEAGLView
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
viewController.wantsFullScreenLayout = YES;
viewController.view = eaglView;
// Set RootViewController to window
if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
// warning: addSubView doesn't work on iOS6
[window addSubview: viewController.view];
}
else
{
// use this method on ios6
[window setRootViewController:viewController];
}
[window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarHidden: YES];
// IMPORTANT: Setting the GLView should be done after creating the RootViewController
cocos2d::GLViewImpl *glview = cocos2d::GLViewImpl::createWithEAGLView(eaglView);
cocos2d::Director::getInstance()->setOpenGLView(glview);
app->run();
return YES;
}
RootViewContoller.view设置为CCEAGLView,CCEAGLView是一个objective c的类,通过重写Touch delegate
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
这3个方法分别,触摸开始,触摸移动,触摸结束。
封装事件
封装事件,就以其中一个为例
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (isKeyboardShown_)
{
[self handleTouchesAfterKeyboardShow];
}
UITouch* ids[IOS_MAX_TOUCHES_COUNT] = {0};
float xs[IOS_MAX_TOUCHES_COUNT] = {0.0f};
float ys[IOS_MAX_TOUCHES_COUNT] = {0.0f};
int i = 0;
for (UITouch *touch in touches) {
ids[i] = touch;
xs[i] = [touch locationInView: [touch view]].x * self.contentScaleFactor;;
ys[i] = [touch locationInView: [touch view]].y * self.contentScaleFactor;;
++i;
}
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
glview->handleTouchesBegin(i, (intptr_t*)ids, xs, ys);
}
此处,最重要的就是glview,它是一个c++类,继承自cocos2d::Ref,由导演类进行管理。函数原型声明:
void handleTouchesBegin(int num, intptr_t ids[], float xs[], float ys[]);
3个参数分别对应:touch的数量,touch指针数组,x坐标数组,y坐标数组。
其他2个也是一样。把获取到的事件,由objective c封装成c++。