2012-05-09 34 views
0

我已經實現了一種在cocos2d中查找像素完美碰撞的方法。但是,如果我不得不縮放對象像素完美的碰撞不起作用。如何在cocos2d中查找縮放sprite中的像素完美碰撞?

 //sprite declaration 
    fruit1=[CCSprite spriteWithSpriteFrameName:@"Burger-Cut1.png"]; 
    fruit1.position=ccp(200,100); 
    [self addChild:fruit1]; 

    fruit.scale=0.5; 


    //find the collision 

    -(bool) isTransparentWithSprite: (CCSprite *)sprite pointInNodeSpace: (CGPoint) point { 
NSLog(@"in function"); 
bool isTransparent = YES; 

unsigned int w = 1; 
unsigned int h = 1; 
unsigned int wh = w * h; 
//ccColor4B *buffer = ccColor4B[4]; 
Byte buffer[4]; 
// Draw into the RenderTexture 
[rt beginWithClear:0 g:0 b:0 a:0]; 

CGPoint oldPos = sprite.position; 
CGPoint oldAnchor = sprite.anchorPoint; 
sprite.anchorPoint = ccp(0, 0); 
sprite.position = ccp(-point.x, -point.y); 

[sprite visit]; 
sprite.anchorPoint = oldAnchor; 
sprite.position = oldPos; 

// read the pixels 
float x = 0;//local.x; 
float y = 0;//local.y; 
glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, buffer); 
//NSLog(@"%d: (%f, %f)", sprite.tag, x, y); 
[rt end]; 
// Read buffer 
ccColor4B color; 
for(unsigned int i=0; i<wh; i++) { 
    //color = buffer[i]; 
    // if untouched, point will be (0, 0, 0, 0). if the sprite was drawn into this pixel (ie not transparent), one of those values will be altered 
    if (buffer[0] || buffer[1] || buffer[2] || buffer[3]) { 
     NSLog(@" "); 
     NSLog(@"%d %d %d %d=== > ",buffer[0],buffer[1],buffer[2],buffer[3]); 
     NSLog(@" "); 
     isTransparent = NO; 
    } 
} 
//delete buffer; 
return isTransparent; 
} 
+0

你如何發送指向方法isTransparentWithSprite?像這樣:[self convertTouchToNodeSpace:touch]? –

+0

這是我的代碼:UITouch * myTouch = [touches anyObject]; CGPoint location = [myTouch locationInView:[myTouch view]]; location = [[CCDirector sharedDirector] convertToGL:location]; CGPoint local = [sprite convertToNodeSpace:touchLocation]; [self isTransparentWithSprite:sprite pointInNodeSpace:local] – banu

回答

0

您的代碼看起來不錯,只是嘗試調試它:

  • 使特殊顏色邊框圖像(如粉紅)
  • 嘗試觸摸到它與規模1(或模擬位置= ccp(0,0)),如果顏色是粉紅色,則嘗試用刻度0.5觸摸

還有一件事,你可能在紋理尺寸爲1x1的設備上有問題。我有這樣的問題一次,並應設置紋理大小爲32x32:[[CCRenderTexture alloc] initWithWidth:32 height:32 pixelFormat:kCCTexture2DPixelFormat_RGBA8888];