平铺贴图碰撞sfml c++平台

Tilemap collision sfml c++ platformer

本文关键字:sfml c++ 平台 碰撞      更新时间:2023-10-16

我在2d平台游戏中遇到了一个问题。因为我刚开始用c++,我有瓷砖碰撞的麻烦。我可以阻止玩家进入贴图,也可以离开贴图,但不知何故他不能沿着贴图移动。

这是检查新位置是否在实体贴图内的函数:

空白地图::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;
    }
}

}

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

空白球员::更新(){

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个像素,远离碰撞区域(适当的方向)。如果你的角没有被正确地移出碰撞区域,它可能仍然在碰撞边界内。