# How to render the sprites for a 2D soft body physics system

This is not a question as to how to achieve soft body physics, but rather if I have a mass-spring system how to modify a sprite with that information. I am using unity so I dont have access to vector based graphics.

If you have a convex shape then what you can do is perform a convex hull operation to get a list of vertices that define the edge. Now find the average position of these points to define the center.

If you already have a list of edge vertices then you can ofcourse skip that step.

These edge points and the center can be used to define triangles as is common in a triangle fan. i.e. the triangles are defined as (center, i, (i + 1) % nEdgeVerts) where i is an index pointing to the next edge vertex. Basically, it's like slicing a pizza.

This needs to be textured, so you will have to set UV values for the vertices. The easiest way I can think to do this is to first set the center point with the uv of (0.5, 0.5). Then find the coordinate of each edge vertex relative to the center. Find the largest value of x and y and scale all coordinates by these values. This will give you X and Y coordinates in the range -1 to 1. All that's left is to do is shift this into the texture UV range, so add 1 and divide by 2.

So roughly;

do for each edge vertex;

  relativePos = edgePos - centerPos;
if (relativePos.X > largestX) largestX = relativePos.X;
if (relativePos.Y > largestY) largestY = relativePos.Y;


then calculate the UV for each vertex using;

  uvCoord.X = ((relativePos.X / largestX) + 1) / 2;
uvCoord.Y = ((relativePos.Y / largestY) + 1) / 2;


Now this will work for soft bodies which start as fairly regular shapes like cicles, rectangles etc. And if the UVs remain fixed, i.e. calculate once when the shape is first created, you should actually see the texture bend and stretch with the body.

For more complex convex shapes the UV algorithm above might not be a good fit and you'll have to try some other way, even just presetting the UVs somewhere.

For concave shapes, like a half moon, you will need to do decompose it into multiple convex shapes. See here and here.