I'm drawing a health bar on top of each player. I transform 3d position to 2d. I would like to draw it smaller when distance increases. Any simple math for that? Let's say bar width is 30 and height is 10 it looks good only on distance == 100. What formula should I use to make it decrease in size when distance increases?

Should resolution of the game be taken into consideration?

  • \$\begingroup\$ This sounds a lot like actual 3D rendering, so any papers/tutorials on it could be useful for you. \$\endgroup\$ – Sturlen Oct 30 '17 at 19:55
  • \$\begingroup\$ @ZEKE it's about math here, width, height and scale based on distance. Rendering is done in 2D. \$\endgroup\$ – Konrad Oct 30 '17 at 20:01

The very complex and hard to understand calculation people do to get an object's size at a specific distance is: divide by Z. Even the big APIs, like DirectX and OpenGL are basically just rasterizing APIs with a depth buffer. The 3d aspect comes from this. So:

Given a width, a height and a distance from the camera Z, the new width and height of the object is:

w' = w / Z
h' = h / Z
| improve this answer | |
  • 2
    \$\begingroup\$ One detail, if you find it looks right at its base scale at referenceDistance = 100 then throw that in as a multiplicative factor: w' = w * referenceDistance / distance - that way the multiplier comes out to 1 at the reference distance you've chosen, and scales appropriately closer & farther away. \$\endgroup\$ – DMGregory Oct 31 '17 at 3:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.