我正在为大学项目创建一个基本按钮事件,我在尝试访问实体的孩子时遇到了问题。
我正在使用Component模型来创建和显示屏幕上的所有对象,一个“按钮”由3个独立的组件组成,TextComponent显示按钮的作用,即“Start Game”,一个创建的SpriteComponent并在文本上方显示图像,以及作为我的按钮的“边界框”的ShapeComponent。此组件仅作为一种事件处理程序运行,检查鼠标是否在形状的边界框内,如果是,则允许用户与其进行交互(如显示消息)。
下面是我的一个按钮的代码。
static shared_ptr<Entity> btnStartGame;
void MainMenuScene::Load() {
//START GAME BUTTON
auto txtNewGame = makeEntity();
auto t = txtNewGame->addComponent<TextComponent>("New Game");
t->getText().setOrigin(t->getText().getGlobalBounds().width / 2, t->getText().getGlobalBounds().height / 2);
txtNewGame->setPosition(Vector2f(280.f, 500.f));
auto sword = makeEntity();
auto s = sword->addComponent<SpriteComponent>();
s->Sprite("Sword.png", IntRect(0, 0, 60, 60));
sword->setPosition(Vector2f(370.f, 540.f));
auto btnStartGame = makeEntity();
auto b = btnStartGame->addComponent<ShapeComponent>();
b->setShape<sf::RectangleShape>(Vector2f(200.f, 105.f));
b->getShape().setFillColor(Color(224, 190, 20)); //just so I can see where it is
b->getShape().setOrigin(b->getShape().getGlobalBounds().width / 2, b->getShape().getGlobalBounds().height / 2);
btnStartGame->setPosition(Vector2f(Engine::GetWindow().getSize().x / 4 - 40.f, 525.f));
}
创建边界框后,我在Update函数中进行验证检查,以查看鼠标当前是否在ShapeComponent的边界框内。我得到btnStartGame实体的组件并得到它的GlobalBounds,完成后,我检查鼠标当前是否在框内但是这行导致错误。
if (btnStartGame->get_components<ShapeComponent>()[0]->getShape().getGlobalBounds().contains(Engine::GetWindow().mapPixelToCoords(sf::Mouse::getPosition())))
{
cout << "level 1 selected" << endl;
}
我在Vector
中的此行遇到了读取访问冲突错误pointer _Unchecked_begin() _NOEXCEPT
{ // return pointer for beginning of mutable sequence
return (this->_Myfirst());
}
有谁知道为什么会这样?我一开始以为它是一个指针错误,但似乎没有解决任何问题。
答案 0 :(得分:0)
解决了这个问题。
我创建了一个shared_ptr,而不是引用我创建的实体,我试图在Load()函数中指向一个新实体。
从btnStartGame中删除Auto解决了问题
btnStartGame = makeEntity();