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

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

  • 相关阅读:
    来电科技-自助租借充电宝
    一次使用NodeJS实现网页爬虫记
    八爪鱼采集器
    杭州市职称系统
    zz
    有道智选-网易效果推广
    Ubuntu10.04下载并编译Android4.3源代码
    poj 1654 Area 多边形面积
    Android利用Looper在子线程中改变UI
    Notepad 快捷键 大全
  • 原文地址:https://www.cnblogs.com/helmsyy/p/3614383.html
Copyright © 2011-2022 走看看