cocos2d中得touch事件主要有四个。
1使用CCtargetedTouchDelegate 实现touch的四个方法 Standard Touch Delegate
@protocol CCTargetedTouchDelegate <NSObject>
/** Return YES to claim the touch.
@since v0.8
*/
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;
@optional
// touch updates:
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;
@end
2)和IOS的touch事件很类似,主要是第一个开始触摸事件的不一样 和第一个参数的不同 CCTageted Touch Delegate
- (BOOL)ccTouchBegan:(NSSet *)touches withEvent:(UIEvent *)event;
@optional
// touch updates:
- (void)ccTouchMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
@end
2一个简单的touch的应用--点击屏幕,小球跟随
1)在init中初始化一个ball
// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super's" return value
if( (self=[super init])) {
ball = [CCSprite spriteWithFile:@"ball.png"];
CGSize size = [CCDirector sharedDirector].winSize;
ball.position = ccp(size.width/2,size.height/2);
[self addChild:ball];
}
return self;
}
2)设置touch代理事件的相应
i 只有触摸开始事件return yes 才可以让触摸事件的后续代理方法触发响应。为了接受这些触摸事件,我们必须使用全局的 dispatcher 方法注册一个目标代理对象。因此需要注册代理
[[director touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
[super onEnter];
那么在哪里设置呢? 一般来说都是在 onEnter方法中设置。并在 onExit方法中取消代理注册
- (void)onEnter
{
CCDirector *director = [CCDirector sharedDirector];
[[director touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
[super onEnter];
}
- (void)onExit
{
CCDirector *director = [CCDirector sharedDirector];
[[director touchDispatcher] removeDelegate:self];
[super onExit];
}
ii 实现代理事件的相应方法
-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
return YES; //这个方法的设置是必须的,要不然end方法不会触发
}
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
CGPoint touchLocation = [touch locationInView:[touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
//通过一系列的转化,最终得到触摸的位置
float velocity = 480.0/3.0; //移动速度
CGPoint moveDifference =ccpSub(touchLocation, ball.position); //获得触摸位置和小球位置的offset(x,y)
float moveDistance = ccpLength(moveDifference); //得到直线距离
float moveDuration = moveDistance/velocity; //计算出 move的time
if(moveDifference.x < 0){ //根据move的x正负设置对应的方向
ball.flipX = NO;
}else{
ball.flipX = YES;
}
id moveAction = [CCMoveTo actionWithDuration:moveDuration position:touchLocation];
[ball runAction:moveAction]; //设置移动
}