Shrink it Box2D prototype – Step 2

In the previous step I showed you how to shrink/expand any kind of polygon.

Anyway in the original game, you can’t expand objects as much as you want, because you need mass to do it, and this adds strategy to the gameplay, because you have to shrink objects to gather the necessary mass to expand other ones.

I suppose the required amount of mass is the difference between the final and the initial mass.

At the same time, when we shrink an object, we’ll gather mass… probably determined by the difference between the initial and the final mass.

When you want to play with masses, the first thing you must setup carefully is the expand/shrink ratio. In the previous step I used a 10% for both shrinking and expanding.

This leads to a glitchy gameplay because if I have a sphere with a radius = 100 and I shrink it by 10% I get a sphere with a radius = 90. But if I expand 90 by 10% I get a sphere with a radius = 99. I don’t get the original sphere. So I cannot use these values, because I need to get the initial object if I expand it and then shrink it or if I shrink it and then expand it.

So in this example I am using 20% shrinking and 25% expanding. This way, our object with radius = 100 shrinked by 20% will have a radius of 80… and a radius = 80 expanded by 25% returns 100 again.

It’s up to you to find a couple of compatible numbers.

About masses, this is the concept: when the player shrinks an object, there isn’t any problem, I just have to compare the old mass with the new one and add the difference to the available mass. To get a body’s mass, use GetMass().

When the player tries to expand an objects, things become a little harder because we can’t know the future mass of the body, unless we want to heavily play with geometry.

So we have to make a little trick: first we remove the original shape, then we create and attach the new, expanded shape to the body, so we can get the mass of the final body. If we have enough mass, then we render the body, otherwise we remove the new shape and restore the old one. Since we do everything before rendering the frame, it will work nicely.

This is the script:

And this is the result:

Click on a body to shrink it, click + SPACE to enlarge it, and look at your mass meter in the lower left corner.

No need to download, simply copy/paste this code in the file you can find in the previous step.

Next time, we’ll add the final gameplay.

  • Hi Emanuele

    Really liked this tutorial. I was looking for a way to resize box2d objects on the fly and this solved the problem.

    Take a look at my game using this techniques
    http://apps.facebook.com/bookpileup

    Thanks

    Mike