I have an array[15][15] with path for my object. 0 is wall, anything else makes path (1->2->3->...->end). It's a reflection of the game field of 450px x 450px(30px x 30px is one field).
For array[15][15] looking like this:
080000000000000
010111011101110
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
010101010101010
011101110111010
000000000000090
I get:
My object moves with some velocity * speed:
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() checks what direction (velocity) it should set, like this:
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);
}
But as you may notice, this will lead for my object to follow path like this:
Because it checks top left corner, and if I move right it should change the origin point, but I can't figure out how to do it. When I tried adding 30 (object bitmap size) if it goest right, it stops at the up -> right corner. What's a solution in here?
Have removed most of my answer, as it appears to misunderstand the question. But I will leave this part about your get_grid
function being crazy. Just use maths (I assume that x
and y
are integers):
Point Enemy::get_grid()
{
return make_point(x / 30, y / 30);
}
Furthermore, if you want to take your grid position and show it in the centre of a tile where each tile is 30 pixels square, then do this:
int pixelX = gridX * 30 + 15;
int pixelY = gridY * 30 + 15;