You are here

A simple animated star field

Sometimes it might look a bit empty between the objects in a typical, simple game.

One way of bringing some life onto the screen is to draw an animated background behind the objects, for example a star field.

A simple way of doing this is to create two classes; Star and StarHandler.

Star.java:

package com.ajomannen.justroids;

public class Star {
    public double angle;
    public double radius;
    
    public Star(double angle, double radius) {
        this.angle = angle;
        this.radius = radius;
    }
    
}

And StarHandler.java:

package com.ajomannen.justroids;

import java.util.ArrayList;
import java.util.Random;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;

public class StarHandler {
    ArrayList<Star> stars;
    private Random random;
    private Paint starPaint;
    private float screenWidth;
    private float screenHeight;
    
    public StarHandler(int noOfStars, float screenWidth, float screenHeight) {
        this.screenWidth = screenWidth;
        this.screenHeight = screenHeight;
        stars = new ArrayList<Star>();
        random = new Random();
        
        starPaint = new Paint();
        starPaint.setColor(Color.WHITE);
        starPaint.setStyle(Style.FILL);
        
        for (int i=0; i<=noOfStars; i++) {
            double angle = Math.toRadians(random.nextInt(360));
            double radius = random.nextDouble() * 400 + 0.001;
            stars.add(new Star(angle, radius));
        }
        
    }
    
    public void setScreenWidth(float screenWidth) {
        this.screenWidth = screenWidth;
    }

    public void setScreenHeight(float screenHeight) {
        this.screenHeight = screenHeight;
    }

    public void update() {
        for (int i=0; i<stars.size(); i++) {
            Star star = stars.get(i);
            star.angle += 0.01;
            star.radius += star.radius * 0.05;
            if (star.radius > 400) {
                star.radius = random.nextDouble() * 10 + 0.001;
                star.angle = Math.toRadians(random.nextInt(360));
            }
        }        
    }
    
    public void draw(Canvas c) {
        for (int i=0; i<stars.size(); i++) {
            Star star = stars.get(i);
            double x = Math.cos( star.angle ) * star.radius;
            double y = Math.sin( star.angle ) * star.radius;
            float startX = (float) (x + screenWidth/2);
            float startY = (float) (screenHeight/2 - y);
            float stopX = startX + 1;
            float stopY = startY + 1;
            c.drawLine(startX, startY, stopX, stopY, starPaint);
        }        
    }

}

 

Then you can use it just as any other handler by calling update() and draw() in your GameEngine.

The result:

Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer