碰撞C ++ 2D游戏,阻止玩家进入方块 [英] Collision c++ 2d game, preventing player from entering tile
问题描述
我已经尝试了好几天,却花了几个小时搜索网络,但无济于事。我在碰撞方面遇到麻烦,可以检测到碰撞,但是我的问题是阻止玩家进入瓷砖。我已经尽力了。我正在使用1代表实体和0代表被动的来检测我的tilemap的碰撞
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;
}
}
此方法正常,我的文本播放器一旦碰撞就会变红使用图块,但我无法弄清楚如何防止玩家进入该图块开始,我目前的设置是尝试禁用移动,但所有发生的情况是玩家进入碰撞时将其设置为true,并且禁用了控件,导致玩家完全卡住了。
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.
我当前的动作非常基本
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.
推荐答案
您需要始终记录玩家转弯之前的位置:
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
和 newX
可以为 -1
, 0
或 1
。如果 newY
或 newX
!= 0
必须为 0
。
newY
and newX
can be -1
, 0
, or 1
. If either newY
or newX
!= 0
, the other has to be 0
.
这篇关于碰撞C ++ 2D游戏,阻止玩家进入方块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!