我有一个数组[15] [15],其中包含我的对象的路径。 0是墙,其他任何东西都是路径(1-> 2-> 3-> ......->结束)。它反映了450px x 450px的游戏领域(30px x 30px是一个领域)。
对于数组[15] [15]看起来像这样:
0800000亿
010111011101110
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
011101110111010
000000000000090
我得到:
我的物体以一定的速度*速度移动:
void Enemy::move()
{
this->get_dir();
this->x += this->velX * this->speed; // velX = -1 is left, 1 is right
this->y += this->velY * this->speed; // velY = -1 is up, 1 is down
}
get_dir()检查它应该设置的方向(速度),如下所示:
void Enemy::get_dir()
{
Point p; // {x, y} struct
p = this->get_grid(); // it tries to calculate X, Y axis into an array number
if (p.y < 14 && path_grid[p.y + 1][p.x] - 1 == path_grid[p.y][p.x])
{
this->velY = 1;
this->velX = 0;
return;
}
/* same goes for rest of directions */
this->velX = this->velY = 0; // if none matched it stops (reached end)
return;
}
Point Enemy::get_grid()
{
int x, y;
for(y = 0;y < 15;y++)
{
if (this -> y >= y * 30 && this->y < (y + 1) * 30) break;
}
for(x = 0;x < 15;x++)
{
if (this -> x >= x * 30 && this->x < (x + 1) * 30) break;
}
return make_point(x, y);
}
但正如您可能会注意到的,这将导致我的对象遵循以下路径:
因为它检查左上角,如果我向右移动它应该改变原点,但我无法弄清楚如何做到这一点。当我尝试添加30(对象位图大小)时,如果它最右边,它会停在up - &gt;右上角。这里有什么解决方案?
答案 0 :(得分:2)
删除了我的大部分答案,因为它似乎误解了这个问题。但是我将把这个部分留给你的get_grid
函数疯狂。只使用数学(我假设x
和y
是整数):
Point Enemy::get_grid()
{
return make_point(x / 30, y / 30);
}
此外,如果您想要获取网格位置并将其显示在每个图块为30像素正方形的图块的中心,请执行以下操作:
int pixelX = gridX * 30 + 15;
int pixelY = gridY * 30 + 15;
答案 1 :(得分:1)
你应该能够从网格中找到下一个开放位置但是应该跟踪最后一次移动,这样你就不会回溯,例如:
void movePlayer(){
const GridMap& gridMap = getGridMap(); //returns the 14x14 grid
const Position& currentPosition = getCurrentPosition(); //returns the current player position
const Position& previousPosition = _getPreviousPosition(); //private helper func
//returns a list of position where the current player at the given position can move to
//at point (x,y) you can move to NORTH,SOUTH,EAST, or WEST one unit, from the gridMap
//using the currentPosition, return the list of cells that the player at the given position can move to.
const PositionList& currentMovablePositions = _getMovablePosition(currentPosition,gridMap);
//return the first matching position that isn't currentPosition or previousPosition
const Position& nextMovePosition = _getNextMovablePosition(currentMovablePosition,currentPosition,previousPosition);
this->animateTo( nextMovePosition );
}