Sunday, April 25, 2010

Space Triangle

Well I got really bored today, and thought I could give back a bit to the community. The end result is a ship (triangle) that floats across a stage. The user controls the ship using keyboard arrow keys. The animation is frame independent. That means I explore a bit about frame time calculations, which in code translate into a variable declaration and three lines of code.

To cut the chase short, here's what you can do with 1 line on top of a hundred in pure Actionscript 3 programming.

Check the source code here.

This triangle is a repeated theme in my experimental work, and has been so since I was back in High School. You can imagine that the math involved is really simple arithmetic. That's the elegance that I appreciate for an introduction.

I will not break the habit of not writing code in this blog, and instead I'll explain the core concepts behind this basic program. For a technical undertaking, the code is extremely self explanatory and is very brief.

The game, as I said before, is simply a little triangle that's controllable using the arrow keys. It slides across the screen.

The states I keep watching are the position and rotation of the triangle (which I get for free after creating a sprite). I also create three variables to keep an eye on velocity on the x-axis (sideways), velocity on y-axis (vertically), and rotation.

Three event listeners are in action, two to watch key strokes (and save them into three additional state variables), and one to be called on each frame (the whole simulation driver).

Beyond that, it's a matter of figuring out how to update velocity and rotational velocity based on the keystrokes, then how to update position and rotation based on the velocity variables. There's a piece of trigonometry on conversion from traingle angle into an acceleration vector.

One more piece is left missing, which is the link between the velocity variables, and the positional ones. This piece is the delta time between frames. To keep the motion frame-independent (as in, the same across all computers regardless of processing power), I calculate the time in milliseconds it takes from each frame to the next one. Although it's quite an extrapolation in terms of numerical precision, it does it's job, and the motion is basically frame independent.

1 comment:

  1. Very neat,

    Brought concepts of a physics engine to simple terms.

    I think a lot, including me, will owe you for that.

    Keep it up.