Ios 检测sprite cocos2d中的特定触摸位置

Ios 检测sprite cocos2d中的特定触摸位置,ios,objective-c,cocos2d-iphone,Ios,Objective C,Cocos2d Iphone,在上图中,黄色代表一个比iPad分辨率更大的精灵。我想允许拖放功能在一个特定的位置,这是在这里表示为白色 我得到的是: -CCActor继承了CCSprite -targetedBoundingBox是根据精灵的白色圆圈的边界框 我想要的是: 如何根据屏幕上的精灵获取触摸位置 我的代码: -(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint touchLocation = [self conv

在上图中,黄色代表一个比iPad分辨率更大的精灵。我想允许拖放功能在一个特定的位置,这是在这里表示为白色

我得到的是: -CCActor继承了CCSprite -targetedBoundingBox是根据精灵的白色圆圈的边界框

我想要的是: 如何根据屏幕上的精灵获取触摸位置

我的代码:

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {

    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    CCActor * newSprite = [self selectSpriteForTouch:touchLocation];
    if(newSprite != NULL){
        //touchLocation should be according to the sprite.
        if (CGRectContainsPoint(newSprite.targetedBoundingBox, touchLocation)) {
            [self spriteSelected:newSprite];
            return YES;
        }
        return NO;
    }
    return NO;
}

在我看来,最简单的方法是计算你的触摸位置和精灵位置之间的差异,因此你的代码应该如下所示:

首先在你的类中定义它

CCPoint relativePosition;
然后从触摸代码内部计算您的触摸位置和精灵位置之间的差异(仅当触摸实际位于精灵内部时才进行,这意味着如果触摸精灵外部,您将不会得到x=-100,y=-999)

代码没有经过测试,只是在我的脑海中写下了它,我肯定有错误,但这是一个你应该朝哪个方向走的提示!,还有一些更好的方法来处理这个问题,这取决于你在做什么,举个例子


如果我说不通,请纠正我:)

根据您的描述,“我想要什么:如何根据精灵而不是屏幕获取触摸位置?”,首先您应该了解,当前Cocos2D在层的级别以集中方式处理所有触摸,而不是在精灵级别

因此,在UIView坐标中接收的触摸必须转换为图层(节点空间)坐标,然后检查触摸是否与相关精灵相交。对于参考实现,您可以选中此项

如果我正确理解了您的问题,您希望进一步确定相关精灵中的精确坐标,那么这是一个基本的问题 directionDistance=(newSprite.x,newSprite.y)-(touchlocation.x,touchlocation.y)在触摸与精灵相交的条件下,获取精灵中心的方向和/或距离,以获取相关精灵内的确切触摸位置

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {

    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
    CCPoint actorPosition = [actor position];

    if (CGRectContainsPoint(actor.targetedBoundingBox, touchLocation)) {
      //You now have the touch position here:
      relativePosition = ccpSub(touchLocation, actorPosition);
      return YES;
    }

    return NO;
}