What is the appropriate way of placing game objects in a 2d game?

I’m developing a 2d game for Android.It will be an endless game.I have some items like coins ,plants and other special items.How can i place them effectively?Are there any algorithm or any suggestion for this?

I’m already know that i have to use random numbers for placing them along x and y axis.It’s important to not placing two different item at the same x and y position.

Answer

I’ve used the following approach to generate apples on a snake clone. It’s very simple, although it has some potential problems depending on your game requirements. But if you know will always be a lot more free locations that occupied locations, it should be enough in practice.

Generate a random location for the X and Y axis separately based on the size of the map, but wrap it in a do...while loop that automatically retries whenever the location is already occupied. Something like:

// Find valid location
int x, y;
do {
    x = random(0, width);
    y = random(0, height);    
} while(IsLocationOccupied(x, y))

// Create object there
SpawnObjectAt(x, y);

The implementation of IsLocationOccupied depends on your game. For instance, for a tile-based game you could simply check the contents of the tile at that location. For example:

bool IsLocationOccupied(int x, int y)
{
    return map[x, y] != TileType.Empty;
} 

For a non-tile based game, you could iterate over all your objects and check if any of them would intersect with a new object spawning at that location. For example:

bool IsLocationOccupied(int x, int y)
{
    Rectangle newBounds = new Rectangle(x, y, objectWidth, objectHeight);
    foreach(Entity entity in entities)
        if(entity.bounds.Intersects(newBounds))
            return true;
    return false;
}

A safer alternative is to somehow keep a list of all the free locations in the screen, and remove one element at random from the list when you need to spawn a new object. This is great in a tile-based game, but even in a continuous environment you can still divide it into an imaginary grid to limit the number of locations.

Attribution
Source : Link , Question Author : droidmachine , Answer Author : David Gouveia

Leave a Comment