Search code examples
cocos2d-iphonecollision-detection

CCRenderTexture size and position in Cocos2d-iphone


I was trying to use CCRenderTexture for pixel perfect collision detection, as outlined in this forum posting:

http://www.cocos2d-iphone.org/forum/topic/18522/page/2

The code "as is" works, and I have integrated it with my project

But I am having trouble doing some of the other things discussed: If I create the renderTexture to be any size less than the screen size, the collision detection doesn't work properly - It seems to show collisions when the sprites are close (<15px) to each other but not actually colliding.

Also I have trouble changing the location of the render texture. Regardless of the position I specify, it seems to go from bottom left (0,0) till the width & height specified. I followed this post:

http://www.cocos2d-iphone.org/forum/topic/18796

But it doesn't solve my problem. I still get bad collisions like specified above. Also, the first post I mentioned on the list contains comments by many users who have resized their textures to 10x10, and repositioned them off screen.

Does anyone have any sample code, so I can see what I am doing wrong? I just use the boilerplate code:

    CCRenderTexture* _rt = [CCRenderTexture renderTextureWithWidth:winSize.width height:winSize.height];

    _rt.position = CGPointMake(winSize.width*0.5f, winSize.height*0.5f);
    [[RIGameScene sharedGameScene]addChild:_rt];
    _rt.visible = YES;

I use cocos2d-iphone 1.0.1


Solution

  • You need to move the sprites you intend to draw into the region of the renderTexture before calling draw or visit. Moving the renderTexture does not change the position of _rt.sprite.

    The intersection rectangle must be in the region of the renderTexture, otherwise you get inaccurate collisions.

    It seems that you cannot change the position of _rt.sprite.

    The solution that I use is to determine the origin (x,y) of the intersection box, and offset both the colliding sprites by that much. This will ensure that the intersection rectangle will have its origin at 0,0. Then I calculate the intersection rectangle again (after ensuring the origin of the intersection rect is 0,0) . Then I follow the instructions in the forum posting.

    When determining the dimensions of the render texture, I ensure that they are at least as large as the intersection rectangle, and I ensure that the intersection rectangle is fully inside the render texture. This way there are accurate collisions. If even part of the intersection box is outside the render texture i get inaccurate collisions, so before drawing into the render texture, make sure you move the sprites you intend to visit so that the intersection box is entirely within the render texture.

    Remember to move the sprites back after you're done. :)