开发者

method for controling and referring character on 2d tile map

I am making a character moving messanger

(2d tile map game looking messanger)

I want each tile to refer which character is on.

in short, my program need to refer character by character's x,y coordinate.

I tried make each tile to have a space for character obj structure.

good point of this method is that each character can be refered by x,y coordinate

but it's been pretty hard to move a character here to there.

copy the object from here to there and delete original x y coordinate's object

and lastly, change obj control pointer(for controlling) from original x,y's object to dest x,y's object.

it is not that straight forward, nor easy to control, nor memory saving.

so I consider a second method.

there are tile array and obj array.

when render the objs, just refer to the obj's x,y.

when user want to move the obj, just change x,y.

but if when refering to the obj comes in issue,

I have to search obj arr开发者_Python百科ay all over.

my question is this.

is there any good method for character(obj) controlling on 2d tile map?

any suggestion would be appreciated.


You didn't specify a programming language, so I will use C# in my examples.

Characters and other objects that exist on a map are usually stored in a separate list, not a 2D array. Each character would store their own x and y coordinates. Something like:

class Character
{
    int x, y;

    public int X
    {
        get{ return x; }
        set{ x = value; }
    }

    public int Y
    {
        get{ return y; }
        set{ y = value; }
    }

}

and you would store them in a list like:

List<Character> characters = new List<Character>();

If you really needed to find a character on a particular tile, you'd do something like this (there's probably a linq way to do this in 1 line, but this is easier to understand and read):

int searchX = 10;
int searchY = 15;
Character characterOnLocation = null;
foreach(Character character in characters)
{
    if(character.X == searchX && character.Y == searchY)
    {
        characterOnLocation = character;
        break;
    }
}

Your draw method should loop through the terrain tiles (like it probably does already), then just loop through the Character array and draw them using their own X and Y coordinates. Something like (using XNA in this example):

foreach(Character character in characters)
{
    spriteBatch.Draw(texture, character.X, character.Y);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜