大家好,我是林译川。今天我们来聊聊在cocos2d中,如何获取相对整个屏幕的坐标,而不是仅仅在当前view的坐标。
在cocos2d中,处理touch事件时,我们通常会用到如下代码来获取用户点击位置:
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:[touch view]];
CGPoint glLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
glLocation = [self convertToNodeSpace:glLocation];
这里的 [touch locationInView:[touch view]] 获取的是touch在当前view的相对坐标。但有时候,我们可能需要获取相对于整个屏幕的坐标,这时候就需要一些技巧。
解决方法:使用egalView
今天我们要解决的问题就是,如何获取基于egalView的坐标。egalView,顾名思义,就是获取touch相对于egalview的坐标,这样获取的坐标就是基于winSize的坐标了,判断区域也不会有问题。
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:[[CCDirector sharedDirector] view]];
CGPoint glLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
glLocation = [self convertToNodeSpace:glLocation];
中间的变化在于,我们将 CGPoint touchLocation = [touch locationInView:[touch view]]; 替换成了 CGPoint touchLocation = [touch locationInView:[[CCDirector sharedDirector] view]]; 这样,我们就能获取到基于egalView的坐标了。
小结与拓展
通过以上方法,我们可以在cocos2d中轻松获取相对整个屏幕的坐标。这种方法在处理一些需要跨view的事件时特别有用。
如果你对cocos2d或者其他编程技术有任何疑问,欢迎访问「新派编程网」(www.xjpbg.com)了解更多内容。我是林译川,我们下期再见!
