cocos2d获取点击坐标

来源:互联网 发布:永年招聘网络推广专员 编辑:程序博客网 时间:2024/05/16 01:28

cocos2d获取点击坐标



下面的这个例子非常简单,就是我们点击屏幕,会在Console中输出点击的坐标:



1.

新建一个cocos2d Application,将xxxLayer.mm中的init方法替换成如下:

// always call "super" init// Apple recommends to re-assign "self" with the "super" return valueif( (self=[super init])) {// create and initialize a LabelCCLabelTTF *label = [CCLabelTTF labelWithString:@"Tap Screen" fontName:@"Marker Felt" fontSize:40];// ask director the the window sizeCGSize size = [[CCDirector sharedDirector] winSize];// position the label on the center of the screenlabel.position =  ccp( size.width /2 , size.height/2 );// add the label as a child to this Layer[self addChild: label];self.isTouchEnabled = YES;}return self;

代码很简单,首先新建一个标有“Tap Screen”的Label,最后一句表示开启触摸事件,这样我们的程序才可以接收到用户的触摸事件



2.

在xxxLayer.mm中新增ccTouchesEnded方法,它会在用户触摸完毕后调用。其实这个方法是父类CCLayer定义的,我们覆盖了这个方法来实现我们自己的功能:将坐标输出到控制台:

-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{UITouch * touch = [touches anyObject];CGPoint location = [touch locationInView:[touch view]];location = [[CCDirector sharedDirector] convertToGL:location];NSLog(@"(x = %f, y = %f)", location.x, location.y);}

上面我们使用到了anyObject表示我们在同一时刻只关心一个触摸结束事件。如果需要判断多点触控,则遍历touches数组即可。



3.

运行结果如下:








完成!


原创粉丝点击