Download

Grid-based Top Down 2D Game - questions

Hello everyone.
I am doing a Pokemon-like game (Top-Down 2D, Grid Based) and i have some questions.

1. What is the simplest method to handle Grid-Based Movement?
Let the player will press Up Arrow - while he is moving top he can’t change direction until he ends moving to next grid.

At the moment i am handling movement this way:
PlayerPawn class is storing grid coords - X and Y.

My Input is set to Action Mappings and i am storing which key is pressed, for example:


InputComponent->BindAction("MoveUp", IE_Pressed, this, &APlayerPawn::MoveUpPressed);
InputComponent->BindAction("MoveUp", IE_Released, this, &APlayerPawn::MoveUpReleased);

void APlayerPawn::MoveUpPressed()
{
	bUp = true;
}
void APlayerPawn::MoveUpReleased()
{
	bUp = false;
}

I don’t wanna to press movement key again after Pawn will finish his movement on his destination so i need to check if the key is still pressed.

Next step - in PlayerPawn tick function i am checking which direction Pawn should move (you know - UP and DOWN are both pressed, or UP and RIGHT).
If Pawn should move - then i set bIsMoving = true (so is for checking if i can change direction or not).
Actor is moved by using FMath::Leprp function (mapping X Y grid-coords to world coords). After he completes move - then set bIsMoving = false, so next input can be handled.

This works pretty well but i wanna ask if there is easier solution for doing this? Cause i feel like i am doing too much unnecessary thing in my solution.

2. Interaction with objects - collisions, collecting, etc.
Before i move my Pawn i need to check if destination is occupied by some static object or if i can collect something (crystal for example).
So my object have flags:


#define F_STATIC 0x0001
#define F_COLLECTABLE 0x0002

For getting object in destination grid i am iterating for each object that is derived from AGameObject:


AGameObject * APlayerPawn::GetXYObject(int x, int y)
{
	TArray<AActor*> FoundActors;
	UGameplayStatics::GetAllActorsOfClass(GetWorld(), AGameObject::StaticClass(), FoundActors);

	for(auto Actor : FoundActors)
	{
		AGameObject * Object = Cast<AGameObject>(Actor);

		if(Object)
		{
			if(Object->GetGridX() == x && Object->GetGridY() == y)
				return Object;
		}
	}

	return NULL;
}

I don’t feel it will be effective if my map will be like 100x100 or 1000x1000 grids.
So here the question - what is the best way to store (or access) objects in 2D Grid-Based game? Some container like map with grid X, Y key?

If you see any grammar mistakes please let me know so i can correct them.