Cocos2d中,我们让CCSprite也可以接受触摸。

来源:互联网 发布:校园网络平台建设计划 编辑:程序博客网 时间:2024/05/21 12:47

cocos2d中,layer的主要任务就是接受用户的触摸,在看本文之前,读者最好了解ios与用户交互的方式,最好也知道cocos2d中

 

是怎么相应用户的触摸到各个layer的。

 

 

      首先我们继承自标准CCSprite,并且遵循CCTargetedTouchDeleget或者CCStandadTouchDeleget

 

    

[cpp] view plaincopy
  1. //  
  2. //  TestSprite.h  
  3. //  touchTest  
  4. //  
  5. //  Created by jeffrey on 10-11-12.  
  6. //  Copyright 2010 __MyCompanyName__. All rights reserved.  
  7. //  
  8. #import <Foundation/Foundation.h>  
  9. #import "cocos2d.h"  
  10. @interface TestSprite : CCSprite<CCTargetedTouchDelegate>   
  11. {  
  12. }  
  13. @end  
 

 

    

[cpp] view plaincopy
  1. //  
  2. //  TestSprite.m  
  3. //  touchTest  
  4. //  
  5. //  Created by jeffrey on 10-11-12.  
  6. //  Copyright 2010 __MyCompanyName__. All rights reserved.  
  7. //  
  8. #import "TestSprite.h"  
  9. @implementation TestSprite  
  10. - (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event  
  11. {  
  12.     if ( ![self containsTouchLocation:touch] )   
  13.     {  
  14.         return NO;  
  15.     }  
  16.     CGPoint pooint =   [self convertTouchToNodeSpaceAR:touch];  
  17.     return YES;  
  18. }  
  19. - (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event  
  20. {  
  21.     CGPoint touchPoint = [touch locationInView:[touch view]];  
  22.       
  23.     touchPoint = [[CCDirector sharedDirector] convertToUI:CGPointMake(touchPoint.x, touchPoint.y)];  
  24.       
  25.       
  26.       
  27.     self.position = CGPointMake(touchPoint.x, touchPoint.y);  
  28. }  
  29. - (void) onEnter  
  30. {  
  31.     [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];  
  32.     [super onEnter];  
  33. }  
  34. - (void) onExit  
  35. {  
  36.     [[CCTouchDispatcher sharedDispatcher]    addTargetedDelegate:self priority:0 swallowsTouches:YES];  
  37.     [super onExit];  
  38. }  
  39. - (CGRect)rect  
  40. {  
  41.     CGSize s = [self.texture contentSize];  
  42.     return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);  
  43. }  
  44. - (BOOL)containsTouchLocation:(UITouch *)touch  
  45. {  
  46.     return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);  
  47. }  
  48. @end  
 

 

     这样我们自己的CCSprite就可以接受触摸了。

 

     rect这个函数,是我们讲sprite自己的坐标映射到自己的坐标系中,

     containsTouchLocation:这个函数就看看我们的触摸点是否在sprite中。

 

     CGPoint pooint =   [self convertTouchToNodeSpaceAR:touch];

     这个就是将相对于layer的touch转化为sprite,然后得出相对与sprite本身的坐标。

 

 

      这样我就能根据触摸sprite的不同位置,对sprite进行不同的控制。

 

      OnEnter是继承自CCSprite的函数,主要作用是把自己注册到相应链中去,

      这样精灵级别就可以接受触摸了。

      相反,OnExit是注销的意思。