A Simple Three-Level Parallax Star Field using XNA
This article was largely destroyed by hackers. Please see this link for a better, complete version.
For my follow-up game to Abduction Action!, I required a three-level parallax star field that could be randomly generated. Somehow I have never done this before (this seems to be a pretty common early game programming task), but it proved not to be too difficult. I created a simple Star class and a Stars class (collection of Stars), which I will share below, that create a rather nice scrolling star field.
I publicly exposed the Speed values on each Star object so you can adjust them individual if you so need to (my game will ultimately change this value as speed increases) though my code has a hard-coded value. Also of interest, allow the stars to move and reset outside the drawable screen area. This will make their looping from the bottom of the screen back to the top not as noticeable to the gamer.
public class Star
{
private Vector2 direction;
private Color drawColor;
private StarLayer currentStarLayer;
private float MAX_POSITION = 1000f;
private float MIN_POSITION = -200f;
public enum StarLayer
{
Top = 1,
Middle = 2,
Bottom = 3
}
private Texture2D texture;
public Vector2 Position
{
get;
set;
}
public Vector2 Speed
{
get;
set;
}
public Star(ContentManager content, StarLayer initialStarLayer)
{
this.direction = new Vector2(0, 1);
this.Speed = new Vector2(0, 50);
this.texture = content.Load<Texture2D>("Background\\Star1");
this.currentStarLayer = initialStarLayer;
switch (initialStarLayer)
{
case StarLayer.Top:
{
this.drawColor = new Color(1f, 1f, 1f, .45f);
break;
}
case StarLayer.Middle:
{
this.drawColor = new Color(1f, 1f, 1f, .3f);
break;
}
case StarLayer.Bottom:
{
this.drawColor = new Color(1f, 1f, 1f, .15f);
break;
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(this.texture, new Rectangle(Convert.ToInt32(this.Position.X), Convert.ToInt32(this.Position.Y),
this.texture.Width, this.texture.Height), this.drawColor);
}
public void Update(GameTime gameTime)
{
// Move each lower layer a little slower than the last.
switch (this.currentStarLayer)
{
case
This article has been view 4467 times.
|