Hey, I am currently making a game where your character is always in the middle of the screen, with the objects moving around you when you press the wasd keys. My game was starting to get laggy, so I decided to store all objects in an array that were outside a certain range of me. The objects initially spawn, and store in the array when I move away, however they won't come back once they have been despawned.
This is the code in MyWorld, where I have the objects being created and stored.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class MyWorld here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class MyWorld extends World
{
public static String CurrentMenu = "World";
boolean open = false;
private boolean eKeyDown = false;
String key;
static Material[] things = new Material[10000];
public MyWorld()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1145, 580, 1, false);
Var.xOffset = 0;
Var.yOffset = 0;
addObject(new Player(), 1145/2, 580/2);
addObject(new Minimap(), 1045, 480);
addObject(new Inventory(), 1200, 800);
addObject(new Crafting(), 1145/2, 580/2);
SpawnStuff();
setActOrder(Minimap.class);
}
public void act()
{
if(CurrentMenu.equals("Crafting")) setPaintOrder(InventorySlot.class, Button.class, Crafting.class, MapIcon.class, Minimap.class, Barrier.class, Player.class);
else if(CurrentMenu.equals("Inventory")) setPaintOrder(InventorySlot.class, Inventory.class, MapIcon.class, Minimap.class, Barrier.class, Player.class);
else setPaintOrder(InventorySlot.class, MapIcon.class, Minimap.class, Material.class, Barrier.class, Player.class, Crafting.class, Button.class);
RespawnThings();
}
public void RespawnThings()
{
for(int i = 0; i < things.length; i++)
{
if(things[i] != null)
{
if(CheckDistance(things[i].locX,things[i].locY) < 2000)
{
addObject(things[i],things[i].locX,things[i].locY);
}
else
{
removeObject(things[i]);
}
}
}
}
public double CheckDistance(double xLoc, double yLoc)
{
double xFromPlayer = Math.abs(572.5 - xLoc);
double yFromPlayer = Math.abs(290 - yLoc);
double dFromPlayer = Math.sqrt((Math.pow(xFromPlayer,2)) + (Math.pow(yFromPlayer,2)));
return dFromPlayer;
}
public void SpawnStuff()
{
for(int i = 0; i < 1000; i++)
{
things[i] = new Tree(Greenfoot.getRandomNumber(10000), Greenfoot.getRandomNumber(10000),i);
}
for(int i = 500; i < 1000; i++)
{
things[i] = new Stone(Greenfoot.getRandomNumber(10000), Greenfoot.getRandomNumber(10000),i);
}
}
}
