zoukankan      html  css  js  c++  java
  • cocos 2d CCSprite 触摸识别 非常有用!!!!!

        cocos 2d 中的CCSprite 无法识别触摸操作,需要自定义类。

        解决思想:找到触摸发生的那个点,判断其是否在sprite的矩形区域内

        完整代码如下:

    //MySprite.h文件
    #import "CCSprite.h"
    #import "cocos2d.h"
    
    //自定义类继承与CCSprite,实现CCTouchOneByDelegate协议
    @interface MySprite : CCSprite<CCTouchOneByOneDelegate>
    @property (nonatomic,copy) NSString* spriteName;
    //定义精灵名属性
    -(id)initWithName:(NSString*)spriteNameT;
    @end
    
    
    //MySprite.m文件
    #import "MySprite.h"
    
    @implementation MySprite
    @synthesize spriteName;
    
    -(id)initWithName:(NSString *)spriteNameT
    {
        if (self = [super init]) {
            spriteName = spriteNameT;
        }
        return self;
    }
    
    -(void)onEnter
    {
        //注册触摸控制
        [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
        [super onEnter];
    }
    
    -(void)onExit
    {
        //取消触摸控制
        [[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
        [super onExit];
    }
    
    
    //get the rect of current sprite
    -(CGRect)spriteRect
    {
        //计算精灵的矩形区域并返回
        return CGRectMake( _position.x - _contentSize.width*_anchorPoint.x,
                          _position.y - _contentSize.height*_anchorPoint.y,
                          _contentSize.width, _contentSize.height);
    }
    //判断触摸点是否在精灵矩形区域内
    -(BOOL)isContainsTouchPoint:(UITouch*)touchT
    {
        CCLOG(@"sprite touch event ______________________________________________");
        CGRect spriteRect = [self spriteRect];
        spriteRect.origin = CGPointZero;
        CGPoint touchPointInView = [touchT locationInView:[touchT view]];
        NSLog(@"touch point in touch view is : %f,%f",touchPointInView.x,touchPointInView.y);
        //转换为GL坐标系
        touchPointInView = [[CCDirector sharedDirector] convertToGL:touchPointInView];
        CGPoint touchPoint = [self convertToNodeSpace:touchPointInView];
        BOOL isTouched = CGRectContainsPoint(spriteRect, touchPoint);
        NSLog(@"%@",isTouched? @"YES" : @"NO");
        if (isTouched) {
            //
            CCLOG(@"sprite is touched here");
        }else{
            NSLog(@"sprite is not touched here");
        }
        
        return isTouched;
    }
    
    //实现触摸协议
    #pragma mark touch one by one delegate
    -(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
    {
        return [self isContainsTouchPoint:touch];
    }
    -(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
    {
        NSLog(@"sprite name is %@",spriteName);
    }
    @end

    这个精灵是可以背捕捉到的。

  • 相关阅读:
    阿里巴巴在线笔试题——第一象限坐标点中,原点处能看到的个数
    不改变元素的顺序的情况下,删除数组中重复的元素
    输入一个字符串,判断最后一个单词的长度
    纯虚函数与虚函数
    如何删除数组中重复的元素
    20180317细节收获
    静态数据变量
    cin的用法
    关于free和delete的使用
    关于malloc/free用法
  • 原文地址:https://www.cnblogs.com/helmsyy/p/3614383.html
Copyright © 2011-2022 走看看