I have a capsule shape that is comprised of a cylinder and two half-sphere end caps, and I want to dynamically resize it. As I stretch the capsule by increasing/decreasing the height of the cylinder, the total volume should remain constant by adjusting the radius. This means, I need to define the radius in terms of height and volume.
My starting equation looks like this:
Total volume = Sphere volume + Cylinder volume
$$W_v = \frac{4}{3}\pi r^3 + h \pi r^2$$
Given this equation, I don't know how to solve for radius (r).
Am I approaching this from the right direction? It seems that, when it comes to weird circle problems, or pi in general, it often comes down to integrating/derivating(??) a solution. I know basic Calc, but I can't see how to use it here. Also, since this is for a computer game and needs to run in realtime, I'm really hoping the solution isn't too ... problematic. ;) I know I can fudge an okay representation, but if the real solution is elegant, I'd rather have that. Plus after circling poor attempts to factor and simplify for a while, I'm genuinely curious to know what the answer is now.
Non-Complex Solution
The math involved for solving for $r$ goes a bit beyond basic calculus, I can spare you the long explanations and tell you that $V = \frac{4}{3}\pi r^3+h\pi r^2$ is solved for $r$ as:
$$\frac{1}{4} \left(-\frac{\sqrt[3]{4 \sqrt{3} \sqrt{12 V^2-\pi h^3 V}+\pi h^3-24 V}}{\sqrt[3]{\pi }}-\frac{\sqrt[3]{\pi } h^2}{\sqrt[3]{4 \sqrt{3} \sqrt{12 V^2-\pi h^3 V}+\pi h^3-24 V}}-h\right)$$
That's the only solution not involving complex numbers.
Complex Soltution
The solution(s) involving complex numbers are:
$$r = \frac{\left(1 \mp i \sqrt{3}\right) \sqrt[3]{4 \sqrt{3} \sqrt{12 V^2-\pi h^3 V}+\pi h^3-24 V}}{8 \sqrt[3]{\pi }}+\frac{\sqrt[3]{\pi } \left(1 \pm i \sqrt{3}\right) h^2}{8 \sqrt[3]{4 \sqrt{3} \sqrt{12 V^2-\pi h^3 V}+\pi h^3-24 V}}-\frac{h}{4}$$
Note that this is two separate solutions due to the flipping of the signs. Also notice the formatting of the "minus-plus sign" and the "plus-minus sign". This means that when $\mp$ is negative, $\pm$ is positive. When $\mp$ is positive, $\pm$ is negative.
Graphical Representation of the Functions
I thought it'd be best to represent the data graphically.
The three functions are labeled in these representations as:
All three functions, transposed onto a single $3D$ graph looks like so:
To further represent the data, we can visualize the functions transforming when we put them into the form $f\left(x \cdot h, \; y \cdot V\right)$:
Note that in this gif, $h$ and $V$ are both running from $-10$ to $10$.