ios - 检测 Sprite cocos2d 中的特定触摸位置

标签 ios objective-c cocos2d-iphone

enter image description here

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

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

我想要的: 如何根据sprite获取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;
}

最佳答案

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

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

CCPoint relativePosition;

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

-(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举个例子

如果我说的不对,请纠正我:)

关于ios - 检测 Sprite cocos2d 中的特定触摸位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14583203/

相关文章:

objective-c - 如何使用 Cocos2d 给 Sprite 添加 Action

javascript - UIWebView 未正确加载 JavaScript - 嵌入式 Facebook 帖子

ios - SpriteKit 中的垂直无限滚动背景

objective-c - 如何调用 Objective C 函数?

objective-c - 我如何在 objc-appscript 中编写以下 rb-appscript ?

objective-c - Xcode for How to call function from one class to another class function in iPhone Apps

ios - cocos2d 3.0如何优先处理触摸吞咽

ios - 在 iOS 上解密 AES-128 加密数据

ios - 关闭 View Controller 使应用程序崩溃(lldb)

iphone - 在 Apple App Store 中为 Normal 和 Retina 显示器发布游戏