我有一个功能可以检查其他玩家在地图上的移动并相应地调整他们的位置,它还会检查玩家是否刚刚进入。
void mapManager::checkForOtherPlayerMovement(int plyId)
{
sf::Packet receivedPacket;
std::vector<player>::iterator it;
player pl(0,0,1);
if(socket->Receive(receivedPacket) == sf::Socket::Done)
{
int header;
receivedPacket >> header;
switch(header)
{
case PACKET_PLAYER_DISPATCHNEWPOSITION:
{
receivedPacket >> pl;
std::cout << pl.plyId << std::endl;
if(plyId != pl.plyId)
{
try
{
if(pl.plyId != 0)
{
std::cout << "DEBUG1" << std::endl;
players->at(pl.plyId-1).posX = pl.posX;
players->at(pl.plyId-1).posY = pl.posY;
}
else
{
std::cout << "DEBUG2" << std::endl;
players->at(pl.plyId).posX = pl.posX;
players->at(pl.plyId).posY = pl.posY;
}
}
catch(const std::out_of_range& oor)
{
std::cout << "Added new player!" << std::endl;
players->push_back(pl); // This crashes
}
}
break;
}
case PACKET_PLAYER_DISPATCHENTEREDMAP:
{
break;
}
}
}
}
因此,基本上当新玩家连接到服务器并且游戏需要将其添加到向量中时,就会发生崩溃。奇怪的是它并没有在 Visual Studio 2010 上崩溃,但是当我更改为 vs 2012 时崩溃了,所以我一定做错了什么。
编辑:这是玩家矢量的创建方式
地图管理器.h
std::vector<player> * players;
地图管理器.cpp
players = new std::vector<player>();
这里我使用了玩家矢量
void mapManager::drawOtherPlayers(int plyId, player *ownPlayer)
{
ownPlayerSprite->SetPosition(ownPlayer->getX(), ownPlayer->getY());
window.Draw(*ownPlayerSprite);
for(std::vector<player>::iterator it = players->begin(); it != players->end(); ++it)
{
spriteToDraw->SetPosition(it->posX,it->posY);
window.Draw(*spriteToDraw);
}
}
我的播放器类:Player.h 和 player.cpp