【问题标题】:cocos2d for iPhone - Touch no longer works correctly after scale适用于 iPhone 的 cocos2d - 缩放后触摸不再正常工作
【发布时间】:2012-07-15 22:27:20
【问题描述】:

我对使用 Cocos2d for iPhone 比较陌生,但我遇到了触摸位置的问题。目前,我只是想在屏幕上触摸和移动精灵,当图层未移动以及平移图层时(在我的情况下,在 X 方向上更改 self.position),这可以正常工作,但是,当我缩放时我的图层(例如:self.scale = .5)触摸不再移动精灵。我做了很多论坛搜索/谷歌搜索,我认为我的问题与我的坐标变换(节点空间/世界空间等)有关,但我不是 100% 确定。我确实注意到,当我缩放时,如果我单击没有缩放的精灵所在的位置,那么我可以移动精灵。这让我相信我的转换没有考虑规模。

这是我目前用来获取触摸位置的坐标变换代码:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *myTouch = [touches anyObject];
    CGPoint location = [myTouch locationInView:[myTouch view]];
    location = [self convertToNodeSpace:location];
    location = [[CCDirector sharedDirector] convertToGL:location];
}

这是检查位置(与上面相同的位置变量)是否正在触摸精灵的代码,尽管我更加确信这段代码是正确的,谁知道呢!

for (CCSprite *sprite in movableSprites) {
    if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {
        NSLog(@"Woohoo, you touched a sprite!");
        break;
    }
}

如果您需要更多信息,请告诉我,感谢阅读!

【问题讨论】:

  • 嗯,我认为您需要在此处使用 convertToWorldSpace,因为您希望该位置不转换为图层空间(已缩放)。不过可能是错的。

标签: iphone objective-c ios ios5 cocos2d-iphone


【解决方案1】:

我认为您应该将带有比例的边界框加倍

   for (CCSprite *sprite in movableSprites) {
    if (CGRectContainsPoint(sprite.boundingBox*sprite.scale, touchLocation)) {
       //touch sprite action
    }
}

关于转换点,如果我需要一个绝对屏幕点,我总是使用:

convertToWorldSpace:CGPointZero. 

我不确定你为什么需要在你的触摸位置使用这个,当我需要忽略它们在父节点中的位置时,我通常会在精灵上这样做。

除此之外,如果您的游戏不是真正的多点触控游戏,您最好使用 ccTouchBegan 而不是 ccTouchesBegan。

【讨论】:

    【解决方案2】:

    使用此函数获取精灵矩形。

    -(CGRect)getSpriteRect:(CCNode *)inSprite
    {
        CGRect sprRect = CGRectMake(
                                    inSprite.position.x - inSprite.contentSize.width*inSprite.anchorPoint.x,
                                    inSprite.position.y - inSprite.contentSize.height*inSprite.anchorPoint.y,
                                    inSprite.contentSize.width, 
                                    inSprite.contentSize.height
                                    ); 
    
        return sprRect;
    }
    
    
    
    - (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch *myTouch = [touches anyObject];
        CGPoint location = [myTouch locationInView:[myTouch view]];
        location = [[CCDirector sharedDirector] convertToGL:location];
    
        for (CCSprite *sprite in movableSprites) 
        {
           CGRect rect = [self getSpriteRect:sprite];
           if (CGRectContainsPoint(rect, location)) 
           {
               NSLog(@"Woohoo, you touched a sprite!");
               break;
           }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多