VB:Tutorials:Starfield Parallax

From GPWiki
Jump to: navigation, search

Many space games these days (including Galaxy) fix the representation of the player (ie. the ship) in the center of the screen for convenience and ease of use. In order to create the illusion of motion under these conditions, we need a convincing starfield! For a starfield to be most convincing, I feel that some depth is required. Some stars should be moving faster than others, implying that this parallax is the result of variable distance from the stars.

But that's just me :) I also like it because it's pretty!

How do you do it? You simply invert the velocity vector of the ship, and multiply by some fraction. This will result in a vector opposite the ship's motion (as it should be, when you move forward, everything around you moves backward, right?) that is somewhat smaller than the ship's total velocity. If you vary this fraction, you'll obtain the depth I spoke of. Check it out:

msngStarX = msngStarX - msngShipSpeed * msngStarRelSpeed * Sin(msngShipHeading) msngStarY = msngStarY + msngShipSpeed * msngStarRelSpeed * Cos(msngShipHeading)

That's it! Do this for a bunch of stars, and vary the value of msngStarRelSpeed between 0.1 and 1.0 and you'll end up with a cool layered starfield! Download the starfield demo source code to see a working implementation.