Using Polar Coordinates in VB
Today, I’ll show you how to use polar coordinates in Visual Basic 2010.
Why?
So, what possible reason could you have for using polar coordinates? Well, polar coordinates can be used to define a vector with a specified direction and speed. Why is this useful? Well, consider the following scenario: You are making a tank game. In this game, the player can rotate their tank, move forwards and backwards, and shoot. Now, if the player is going to shoot a bullet after rotating, then the bullet needs to go at a specific speed in a specific direction. However, Visual Basic doesn’t permit this type of movement. It only allows you to alter the X and Y coordinates of a point directly. So how much should you move an object if you want it to move at, say, 2 pixels per frame at a direction of 235 degrees? Well, if you look at that, that’s a polar coordinate of (2, 235)! So all we need to do is convert this polar coordinate to Cartesian coordinates, and we’re good to go!
The Formulas
At this point, you may be wondering, ‘How on earth do I convert polar coordinates to cartesian coordinates?’ The answer is… drum roll please… triginometry!
So, without further adue, the formulas are:
Polar to Cartesian: ((m * cos (d)), (m * sin(d)))
In this formula, m stands for the magnitude (or speed) of the polar coordinate, and d stands for the direction of the coordinate. So the x of the Cartesian coordinate is the magnitude times the cosine of the direction, and the y of the Cartesian coordinate is the magnitude times the sine of the direction.
Cartesian to Polar: ((sqrt(x^2 + y^2)), (atan(y / x)))
In this formula, the magnitude (aka speed) of the polar coordinate is the square root of the sum of x squared and y squared, or sqrt(x^2 + y^2) (And yes, that’s the Pythagorean theorem). The direction of the polar coordinate is the inverse tangent of y divided by x.
The Code
The code to implement the above two formulas is fairly straightforward, except for the fact that VB uses radians instead of degrees. I won’t write down all of the code here, but here is the VB project as a downloadable zip: AdvancedMath.
That’s all for today. See ya’ soon!

November 29, 2011 at 6:46 PMPython Tuesdays – The kickoff! « Defenestration Coding