위치를 GameObject
에 저장하고 개인 필드와 위치를 수정하는 단일 기능을 사용하여 위치가 일관성을 유지하는 것이 좋습니다. 위치는 GameObject의 private 멤버 일 수 있으며 2D 배열은 Map 클래스의 private 멤버 여야합니다. 그런 다음 객체를 이동할 수있는 Map 클래스의 함수를 정의합니다. 이 함수는 배열과 객체에 저장된 위치를 업데이트해야합니다. GameObject의 위치에 대한 Map 클래스 액세스를 부여하는 방법은 프로그래밍 언어에 따라 다릅니다. Java에서는 package-private 함수 (기본 액세스 수준)를 구현하고 동일한 클래스에서 Map 및 GameObject를 정의 할 수 있습니다. C#에서는 내부 함수를 정의하고 동일한 어셈블리에서 C++로 Map 및 GameObject를 정의 할 수 있습니다 Map.move 함수를 GameObject의 친구로 만들 수 있습니다. GameObject의 보호 된 비공개 멤버에 대한 액세스 권한을 부여합니다.
이 접근법의 유일한 단점은 실수로 배열을 업데이트하지 않고 GameObject 내에서 GameObject의 위치를 수정할 수 있다는 것입니다. 이를 방지하려면 각 오브젝트의 위치를 Map-Class의 맵/사전에 저장할 수 있습니다. C++에서는 대략 다음과 같습니다.
#include<map>
class GameObject {}; //don't store the location here
struct Location {
int x,y;
};
class Map {
private:
//the 2D array containing pointers to the GameObjects
GameObject* array[WIDTH][HEIGHT];
//a map containing the locations of all the GameObjects, indexed by a pointer to them.
std::map<GameObject*,Location> locations;
public:
//move an object from a given location to another
void move(int fromX, int fromY, int toX, int toY) {
GameObject* obj = array[fromX][fromY;
array[toX][toY] = obj
array[fromX][fromY] = 0;
locations[obj].x = toX;
locations[obj].y = toY;
}
//move a given object to a location
void move(GameObject* obj, int toX, int toY) {
Location loc = locations[obj];
move(loc.x, loc.y, toX, toY);
}
//get the location of a given object
Location getLocation(GameObject* obj) const {
return locations[obj];
}
};