a game of mathball


I had a simple gameplay loop of pitching and hitting in their most basic form but could tell the pitching "model" needed something a little more sophisticated than slowly increasing the y coordinate of the ball object as it moved from the pitcher's mound to home plate. That would have worked okay with something closer to an overhead 2d perspective, but if I wanted the home plate cam I was going to have to implement some perspective calculations.

After a  little searching for the proper keywords ("transform world space to screen space") I found this tutorial by Munim Munna which gave me exactly the math I needed:

https://github.com/monim67/perspective-vue

I needed to calculate y' as a point translated from an overhead rectangle to a "tilted" trapezoid. The math to do this is pretty simple and is at the bottom of linked tutorial. I got thrown off the scent for a while because I didn't notice the diagrams in the article were math diagrams with lower left origin, while my code is a pixel grid where 0,0 is in the top left corner. This had the effect that points moving closer to the viewer would appear to slow down as they approached, which is the opposite of actual physics. Once somebody pointed out I had the map upside down, it was easy to adjust the equation to work as desired.

The ball moves properly through the y axis now, I still need to implement the other two dimensions but the math for those should be even easier. I have also gotten a sense for why actual 3d engines use quaternions and matrix multiplication of vectors and advanced math to avoid perspective distortion.

Leave a comment

Log in with itch.io to leave a comment.