【问题标题】:Detect specific touch location within a sprite cocos2d检测 sprite cocos2d 中的特定触摸位置
【发布时间】:2013-01-29 12:43:46
【问题描述】:

在上图中,黄色代表一个大于 iPad 分辨率的精灵。我想在此处以白色表示的特定位置允许拖放功能。

我拥有的是: - CCActor 继承 CCSprite -targetedBoundingBox是根据精灵的白色圆圈的boundingBox。

我想要的: 如何根据精灵而不是屏幕获取touchLocation?

我的代码:

-(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;
}

【问题讨论】:

    标签: ios objective-c cocos2d-iphone


    【解决方案1】:

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

    首先在你的类中全局定义这个

    CCPoint relativePosition;
    

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

    -(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;
    }
    

    代码没有经过测试,只是在我的脑海中写下来,我确定有错误,但它是你应该往哪个方向前进的提示!,也取决于你在做什么,有更好的方法处理此问题,以this post 为例

    如果我不明白请纠正我:)

    【讨论】:

      【解决方案2】:

      根据你的描述,“我想要什么:如何根据精灵而不是屏幕来获取touchLocation?”,首先你应该明白,目前Cocos2D在层级集中处理所有的触摸,而不是在精灵级别。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多