I have a game that I am writing in Java. It is a top down RPG and I am trying to handle movement in the world. The world is largely procedural and I am having a difficult time tackling how to handle character movement around the world and render the changes to the screen. I have the world loaded in blocks which contains all the tiles.
How do I tackle the character movement?
I am stumped and can't figure out where I should go with it.
EDIT: Well I was abstract with the issue at hand.
Right now I can only think of rigidly sticking everything into a 2D array and saving the block ID and the player offset in the Block or I could just "float" everything and move about between tiles so to speak.
Answer
Use World Coordinates
(Or as you put it, float everything.)
World coordinates are what you generally work with, and there's plenty of reasons for that. They're the most simple and intuitive way of representing your position in the world, and the only way of really comparing the positions of any two entities in the same world.
You gain nothing but work by having him be tracked within individual blocks. Well, one advantage is you get to determine which block he's in, but you can already calculate that with world coordinates.
The rest of this answer will be an explanation of how to calculate the world block a player is in based on his world coordinates.
I'll write the code snippet as if you have a 2D vector class named Vector2
- the kind of vector you find in geometry, not the Vector
list type offered by java.util
. If you don't have any geometric Vector classes, you should find some online or write some yourself (anyone know any quality geometry libraries for Java?)
The Vector2 class will have an X
field and a Y
field, which are public numbers (doesn't matter which numeric type here).
// Current player X,Y position in the world
Player.Position.X, Player.Position.Y
// An array of map blocks with consistent width and height
Block[x][y] blocks = World.GetBlocks();
// We'll wing it with an example global width/height for all blocks
Block.GetWidth() == 100;
Block.GetHeight() == 100;
// To ensure we're on the same page:
// blocks[0][0] should be at position (0,0) in the world.
// blocks[2][5] should be at position (200,500) due to the width/height of a block.
// Also:
// Assuming (0,0) is in the top-left of the game world, the origin of a block
// is its top-left point. That means the point (200,500) is at the top-left of
// blocks[2][5] (as oppose to, say, its center).
public Vector2 GetPlayersBlockPosition() {
Vector2 blockPosition = new Vector2();
blockPosition.X = (int)(Player.Position.X / Block.GetWidth());
blockPosition.Y = (int)(Player.Position.Y / Block.GetHeight());
return blockPosition;
}
public Block GetPlayersBlock() {
Vector2 bp = GetPlayersBlockPosition();
return blocks[bp.X, bp.Y];
}
Block block = GetPlayersBlock();
2 functions > all the mess of within-block tracking and inter-block transferring
No comments:
Post a Comment