I had to make a function that morphed the contents of an area in a Cocos2d game recently and I came across the problem of blending the effect inside my affected area with the outside. To overcome this and remove the sharp transition that was visible I created a couple of damping functions – one for a circular area and the other for a rectangular area. As you will see the rectangular function will work for a circular area but depends on coordinates rather than distance from centre.

The radial function takes the cosine of the distance from the center of the circle area and scales according to the size of the circle. We add 1 and divide by two to make the function scale over 0 to 1 rather than -1 to 1.

\frac{cos\big(\pi\sqrt{x^{2}+y^{2}}\big)+1}{2}

The rectangular function takes the cosine of the distance of the point from the center in the x and y planes and multiplies to give the resulting 2d profile.

\frac{cos(\pi x)+1}{2}.\frac{cos(\pi y)+1}{2}

The two profiles are shown here:

 The top chart shows the radial profile and you can see that the corners are ticking up as the next bandstarts. The lower chart is nice and flat in the corners which is perfect for a square or rectangular damping function.

The functions are:

+(float)dampeningMultiplierWithdistanceFromCenter: (float)delta inCircleWithRadius:(float)radius
{
    return (cos(M_PI*radius)+1)/2;
}
+(float)dampeningMultiplierWithPointRelativeToCenter: (CGPoint)delta inRect:(CGSize)rect
{
    return ((cos(M_PI*(delta.x/(rect.width/2)))+1)/2)*((cos(M_PI*(delta.y/(rect.height/2)))+1)/2);
}

As the title of this post suggests I used these in developing an iOS game with Cocos2d-iPhone but you can easily adapt this to pretty much any situation.

I hope this helps someone 🙂