cocos2d获取点击坐标

cocos2d获取点击坐标



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



1.

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

	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init])) {
		
		// create and initialize a Label
		CCLabelTTF *label = [CCLabelTTF labelWithString:@"Tap Screen" fontName:@"Marker Felt" fontSize:40];

		// ask director the the window size
		CGSize size = [[CCDirector sharedDirector] winSize];
	
		// position the label on the center of the screen
		label.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.

运行结果如下:








完成!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值