Collision c++ 2d game, preventing player from entering tile

瘦欲@ 提交于 2019-12-10 17:49:30

问题


I've tried for several days and spent hours searching the web to no avail. I'm having trouble with collision, i can detect the collision but my problem is preventing the player from entering the tile. I've tried all i can think of. I'm detecting the collision of my tilemap using 1 for solid and 0 for passive

for(int i = 0; i < tiles.size(); i++)
    {
        if(colMap[tiles[i].y][tiles[i].x] == 1)
        {
            myrect.setFillColor(sf::Color::Red);
            collide = true;
            break;
        }
        else
        {
            collide = false;
            break;
        }
    }

This works ok, my text player turns red once colliding with the tile but i cant figure out how to prevent the player entering that tile to begin with, my current setup i tried to disable movement but all that happens is the player enters the collision is set to true and the controls disabled which results in the player stuck completely.

my current movement is very basic

if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
    if(walking == false)
    {
        //colCheck();
        if(!collide)
        {
        nextspot = x - tilesize;
        move[LEFT] = true;
        walking = true;
        }else
        {
            std::cout << "Collsion!" << std::endl;
        }
    }
}

Any help greatly appreciated.


回答1:


You'll need to always record where your player has been one turn before:

static int prevY, prevX;

for(int i = 0; i < tiles.size(); i++)
{
    if(colMap[tiles[i].y][tiles[i].x] == 1)
    {
        myrect.setFillColor(sf::Color::Red);
        collide = true;

        /* Return Player To Where He's Been */
        colMap[prevY][prevX] = 1;

        break;
    }
    else
    {
        collide = false;
        break;
    }
}

Another method would be to look ahead before moving:

for(int i = 0; i < tiles.size(); i++)
{
    /* Look Ahead (Depends On Which Way He's Trying To Go)*/
    if(colMap[tiles[i].y + newY][tiles[i].x + newX] == 1)
    {
        myrect.setFillColor(sf::Color::Red);
        willCollide = true;
        break;
    }
    else
    {
        willCollide = false;
        break;
    }
}

newY and newX can be -1, 0, or 1. If either newY or newX != 0, the other has to be 0.



来源:https://stackoverflow.com/questions/20777875/collision-c-2d-game-preventing-player-from-entering-tile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!