Thursday, October 4, 2012

Orbit Math :(

One of the biggest challenges I faced with Oribit, was the amount of math involved simply because the game is so circle oriented.

The ship’s movement code is based off a piece of code that creates orbits ala planets. Which for that purpose, it would work great. If you just hold down the left or right arrow keys, the ship orbits at a smooth, consistent rate that looks convincing.

However, I needed to break that code in order to allow changes in direction. Here is what was needed to just move left:


//Used to fix ship Twitch
if (!left)
{
angle += spaceshipSpeed + 1;
}
//Circle Math :<

var rad:Number = angle * (Math.PI / 180);

display.x = origin.x + (Math.cos(rad) * radius);
display.y = origin.y + (Math.sin(rad) * radius);

angle += spaceshipSpeed;

display.rotation = angle - 90;

left = true;


And one of the first things you might notice from playing the game is that changing direction is not perfect. The ship just doesn’t quite go to exactly where it should. The reason is when there is a change in direction the sin/cos numbers flip creating a different angle which is a massive pain. My little fix for that was the left bool, which tried to counteract it to a limited degree of success.

Getting the bullets to travel in a straight line, based on the parent object (whatever is firing the bullets) rotation. This was a key problem which was also eventually solved with math


display.rotation = parentRotation - 90;

vy += Math.sin(degreesToRadians(display.rotation)) * bulletSpeed;
vx += Math.cos(degreesToRadians(display.rotation)) * bulletSpeed;

public function degreesToRadians(degrees:Number) : Number
{
return degrees * Math.PI / 180;
}


All this was before any gameplay was actually realized.

Bullet Patterns underwent a huge overhaul after I discovered that the built-in function of Event Timers in AS3 cause problems quickly. For those who don’t understand here is an example. The Eye (The big floating thing that inexplicably tries to kill you) has 36 individual bullet spawners. When a pattern is created I tell each bullet spawner how fast it should spawn bullets and how many.

Originally the bullet spawner would set a timer based on how fast the bullets were supposed to spawn, when the timer hit 0, a bullet would then spawn. Simple right? Well, the inherit problem with timers is that different computers do those timer calculations quicker than other sometimes. This causes all sorts of scary things like patterns becoming desynced.

So the solution was to make everything dependent on the frame rate. Frame Rates are set in-game and no matter how fast a computer is, it stays consistent. Thank you Matt for showing me what real programmers do.

No comments:

Post a Comment