This site requires JavaScript, please enable it in your browser!
Greenfoot back
bleeblob43
bleeblob43 wrote ...

2016/6/1

Checking if there is an actor is at a specific spot in the world

bleeblob43 bleeblob43

2016/6/1

#
I've been working on a game. In the game, the background is made up of Ground objects. The 'background' is a grid of these Ground objects. I did this because I want each tile to respond to light sources individually. However, I also want the game to be infinite in all directions. To avoid slowing the game down, I want to remove Ground objects if they arent within a 600 pixel radius of the player. That was the easy part. I also wanted to add Ground objects within a 600 px radius of the player. I was wondering if there is some sort of method to check if there is already a ground peice at a given location. I want to do something along the lines of:
if(!isActorAt(Ground.class,40,89)){
    getWorld().addObject(new Ground(),40,89);
}
the 40 and 89 are x and y values(the location to check)
bleeblob43 bleeblob43

2016/6/1

#
never mind i found the method
danpost danpost

2016/6/1

#
Instead of adding and removing the Ground objects, you could just have them move themselves when the player is out of range to a new location along the same horizontal or vertical to the next non-ground location (like leap-frogging). To do that, you could have something like the following method in the Ground class called last from its act method:
public void checkLocation()
{
    // do nothing if player is not in world
    if (getWorld().getObjects(Player.class).isEmpty()) return;

    // get required info
    Player player = getWorld().getObjects(Player.class).get(0);
    int range = 1+600/getWorld().getCellSize(); // the 600 can be made larger if needed
 
    // horizontal out-of-range check/relocation
    int xOffset = player.getX()-getX();
    int xDirection = (int)Math.signum(xOffset);
    if (Math.abs(xOffset) > range) setLocation(getX()+xDirection*range*2, getY());

    // vertical out-of-range check/relocation
    int yOffset = player.getY()-getY();
    int yDirection = (int)Math.signum(yOffset);
    if (Math.abs(yOffset) > range)  setLocation(getX(), getY()+yDirection*range*2);
}
The initial Ground objects in the world should start within range, or just out of range, of the player so that they will not initially move when the scenario is started and before the player moves. The way I wrote the code, you will need to build a square grid of Ground objects with the player in the middle.
You need to login to post a reply.