![](/img/trans.png)
[英]Calculating in an optimized way pow(x,y) for 0<=x<=1 and 1<y<2 in C++
[英]Calculating grid cords from (x, y) position C++
我有一个带有对象路径的array [15] [15]。 0是墙,其他任何东西都构成路径(1-> 2-> 3-> ...-> end)。 这反映了450px x 450px(30px x 30px是一个字段)的游戏字段。
对于array [15] [15]如下所示:
080000000000000
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(对象位图大小)(如果正确)时,它停在向上->右上角。 这里有什么解决方案?
删除了我的大部分答案,因为它似乎误解了这个问题。 但是我将离开这部分,让您的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;
您应该只能够从网格中找到下一个未平仓头寸,但应该跟踪上一举动,以免回溯,例如:
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 );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.