好的,所以这对我来说很难说出来,但是可以了。

我正在尝试创建一个类似于Crazy Taxi的游戏,该游戏是自上而下的 View 游戏,玩家可以控制汽车。在红色框下方的图片中,是我的车,而我将 map 的其余部分划分为网格。汽车和网格的大小为25 x 25,因此,汽车的尺寸为1网格。现在,我尝试研究如何与 map 网格进行碰撞,并且得到了以下链接:
http://www.emanueleferonato.com/2012/05/24/the-guide-to-implementing-2d-platformers/

所以我在CheckCollision函数中想到了这个:

    // which tile are you at?
    int tileX = (int) playerPos.x  / TILE_SIZE;
    int tileY = (int) playerPos.y / TILE_SIZE;

    if (right)
    {
        if (m_Map->GetGrid(tileX + 1, tileY).GetID() == ROAD_BORDER_LEFT  ||
            m_Map->GetGrid(tileX + 1, tileY).GetID() == ROAD_BORDER_RIGHT ||
            m_Map->GetGrid(tileX + 1, tileY).GetID() == ROAD_BORDER_UP ||
            m_Map->GetGrid(tileX + 1, tileY).GetID() == ROAD_BORDER_DOWN)
        {
            return true;
        }
    }

    if (up)
    {
        if (m_Map->GetGrid(tile_X, tile_Y - 1).GetID() == ROAD_BORDER_LEFT  ||
            m_Map->GetGrid(tile_X, tile_Y - 1).GetID() == ROAD_BORDER_RIGHT ||
            m_Map->GetGrid(tile_X, tile_Y - 1).GetID() == ROAD_BORDER_UP ||
            m_Map->GetGrid(tile_X, tile_Y - 1).GetID() == ROAD_BORDER_DOWN)
        {
            return true;
        }
    }

我检查右,左,上和下。现在的问题是,我意识到该链接适用于具有固定轴的游戏(例如侧面滚动游戏)。对于我的游戏,我可以旋转汽车,然后根据该轴向前移动。例如。如果我的车向右行驶,而我按“w”,则汽车将向右行驶而不是向上行驶。

因此,我的问题应该是:根据我的汽车所面对的方向,如何跟踪要检查的栅格?我只想检查汽车的正面,背面和侧面。例如。如果前面有什么,我不能前进。

PS。我可以在 map 内自由移动。这意味着我的车可以在两个网格之间。

其他信息:

我的前进车代码:
if (CInputManager::GetInstance()->GetKeyDown('w') &&
        !CheckCollision(m_Player->GetPosition(), false, false, true, false))
{
    // increase acceleration
    m_Player->MoveForward();

我的右转代码:
if (CInputManager::GetInstance()->GetKeyDown('d') /*&&
             !CheckCollision(m_Player->GetPosition(), true, false, false, false)*/)
    {
        m_Player->TurnRight();
        // inside the TurnRight function is:
        // using polar coordinates as direction
        /*
        m_fDirAngle+=6; // its plus instead of minus because of the orthoganal axises

        if (m_fDirAngle >= 360)
        {
            m_fDirAngle = 0;
        }
        */

这就是我移动汽车的方式:
Vector2 CCar::GetDirection(void)
{
    // useful link: http://www.mathsisfun.com/polar-cartesian-coordinates.html
    // remember to convert to radians and remember to -360 because of the different rotation (cc vs clockwise)
    double deltaRadian = m_fDirAngle * (PI/180.0);

    m_dir.Set( cos( deltaRadian ), sin( deltaRadian ));
    return m_dir;
}

void CCar::Update()
{
    Vector2 move;
    move.Set(GetDirection().x * (m_fSpeed + m_fCurAcceleration), GetDirection().y * (m_fSpeed + m_fCurAcceleration));

    this->m_pos.Set(m_pos.x + move.x, m_pos.y + move.y);
}

最佳答案

本质上,您要查找的是无轴对齐的矩形交点。这是有关如何处理这种情况的一些信息:

Area of rectangle-rectangle intersection

关于c++ - 如果可以旋转角色,如何使用网格图进行碰撞检测?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22329391/

10-17 01:27