How can I make entities render once?

Me and a friend are working on a game where the player is in space, and we decided to add stars to the background. It worked well but the more stars there are the more the game lags, is there anyway to make them draw once and then stop lagging game so much? With only one star the game has over 4000 fps, with 60 stars the game has only 70 fps.

Here’s our code

public class Star extends Entity {

	private int tex, rot;
	private boolean rotBool;

	public Star(float x, float y, int tex, int rot, boolean rotBool) {
		super(x, y, 5, 5);
		this.tex = tex;
		this.rot = rot;
		this.rotBool = rotBool;
		setLocation(x,y);
	}

	@Override
	public void update(GameContainer container) {
	}

	@Override
	public void draw(Graphics g) throws SlickException {
		Image img = new Image(Core.RES + "Star" + tex + ".png");
		if (rotBool){
			img.rotate(rot);
		}
		img.draw(getX(), getY());
	}
}
	@Override
	public void render(GameContainer container, Graphics g) throws SlickException {
		g.setBackground(new Color(71, 126, 255));
		for (Star s : stars) {
			s.draw(g);
		}
		for (Entity e : entities) {
			e.draw(g);
		}
	}

while (stars.size() < 60) {
			int randX = new Random().nextInt(container.getWidth() - 10);
			int randY = new Random().nextInt(container.getHeight() - 10);
			int randFile = new Random().nextInt(5) + 1;
			stars.add(new Star(randX, randY, randFile, new Random().nextInt(359), new Random().nextBoolean()));
}

Perhaps because you are reloading the same image every render?

Image img = new Image(Core.RES + "Star" + tex + ".png");

You should instead load it once somewhere outside the star class, and reference that image every time you draw the star.

Essentially, you are calling this around a hundred times a second.

How can I stop reloading them? I tried putting the for loop handling stars in init() and it didn’t render them.

You are loading the same image a bunch of times, which is very taxing on the FPS. Instead, maybe try something like this:


public class Star extends Entity {
   // Static, since it should only be loaded once
   private static Image starImage;

   // Meanwhile in the constructor...

      // If it has not been loaded yet, load it
      if(starImage == null)
         starImage = new Image(Core.RES + "Star" + tex + ".png");

   // Meanwhile in the render...

      // Draw the image that you have already loaded ONCE
      starImage.draw(getX(), getY());

Thanks! That worked.

Since stars are entities you could just add them to the entities list and not keep a separate list for them.

In my opinion, you should keep the resources in a single place, and load them before you are starting your game. I tend to create a class called as [icode]Resources[/icode] which contains all the resources as public static variables. So I can use them like, say


Resources.STAR.draw(getX(), getY());

Whenever I need that to be rendered. That helps you when the resources you need to use starts increasing in number.