Tilemap碰撞sfml c ++平台游戏

时间:2014-06-05 17:24:49

标签: c++ collision-detection sfml

我的2d平台游戏有问题。因为我刚刚开始使用c ++,我遇到了瓷砖碰撞问题。我能够阻止玩家进入瓷砖并且能够远离它,但不知何故他不能沿着瓷砖移动。

这是用于检查新位置是否在实心图块内的功能:

void Maps :: drawColMap(Player& _player){

for (int i = 0; i < _player.tiles.size(); i++)
{
    if (colMap[_player.tiles[i].y][_player.tiles[i].x] == 1) //solid tile = 1
    {
        _player.willCollide = true;
        break;
    }
    else {
        _player.willCollide = false;
    }
}

}

以下是移动播放器的代码:

void Player :: update() {

sf::Vector2f newPosition;  
sf::Vector2f oldPosition;

oldPosition.x = playerImage.getPosition().x; // store the current position
oldPosition.y = playerImage.getPosition().y;

newPosition.x = playerImage.getPosition().x; // store the new position
newPosition.y = playerImage.getPosition().y;

if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
    source.y = Left; //sprite stuff
    moving = true;
    newPosition.x -= 2;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{

    source.y = Right;
    moving = true;
    newPosition.x += 2;
}


if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{

    source.y = Up;
    moving = true;
    newPosition.y -= 2;

}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{

    source.y = Down;
    moving = true;
    newPosition.y += 2;
}

if (!(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::Right) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down)))
{
    moving = false;
}

//create corners to check collision

bottom = newPosition.y + 32; //tile size is 32 px
left = newPosition.x;
right = newPosition.x + 32;
top = newPosition.y;

sf::Vector2i topLeft(sf::Vector2i((int)left / 32, (int)top / 32)); // get the corners of the new position
sf::Vector2i topRight(sf::Vector2i((int)right / 32, (int)top / 32));
sf::Vector2i bottomLeft(sf::Vector2i((int)left / 32, (int)bottom / 32));
sf::Vector2i bottomRight(sf::Vector2i((int)right / 32, (int)bottom / 32));

tiles.clear();

tiles.push_back(topLeft);
if (std::find(tiles.begin(), tiles.end(), topRight) == tiles.end()) tiles.push_back(topRight);  //check the corners
if (std::find(tiles.begin(), tiles.end(), bottomLeft) == tiles.end()) tiles.push_back(bottomLeft);
if (std::find(tiles.begin(), tiles.end(), bottomRight) == tiles.end()) tiles.push_back(bottomRight);

//if no collision set the position to the new position
if (!willCollide)                
    playerImage.setPosition(newPosition);
else
    playerImage.setPosition(oldPosition);  //if collision then set the position to the previous position

}

感谢任何帮助!

//编辑1

我尝试记录碰撞并且说即使我没有按任何东西,玩家仍然在碰撞区域。但是我如何阻止玩家进入?我找不到问题。

//编辑2

我想我发现了另一个问题。 碰撞检查应该在移动玩家之前和移动新位置之后运行。

1 个答案:

答案 0 :(得分:0)

在玩家发生碰撞后,您改变位置,将其移动距离碰撞区域(适当的方向)1个像素。如果角落没有正确地移出碰撞区域,那么你的角落可能仍在碰撞范围内。