当按下 SFML C++时,如何在数组中分配值
How do I assign a value in an array when a mouse is pressed SFML C++
我正在尝试制作一个程序,您可以在其中选择形状选项,然后绘制它。为了允许多个形状,我创建了一个创建形状的类向量(形状是使用所选函数设置的(。我的问题是鼠标单击太长,因此它会将其分配给矢量中的所有内容,因此您无法创建新形状。我的逻辑有问题,还是代码有问题?
这是我的尝试:
for (auto& it : onCanvas) {
if (Mouse::isButtonPressed(Mouse::Left)) {
if (mousepointer.getGlobalBounds().intersects(circleOption.getGlobalBounds())) {
it.chosen(circles);
}
if (mousepointer.getGlobalBounds().intersects(rectOption.getGlobalBounds())) {
it.chosen(rectangle);
}
if (mousepointer.getGlobalBounds().intersects(triOption.getGlobalBounds())) {
it.chosen(triangles);
}
if (mousepointer.getGlobalBounds().intersects(it.shape.getGlobalBounds()) || it.dragging) {
it.shape.setPosition(mousepointer.getPosition());
it.dragging = true;
}
}
if (!Mouse::isButtonPressed) {
it.dragging = false;
}
win.draw(it.shape);
}
你的源代码有点不完整(什么是onCanvas
和mousepointer
(。但我想问题是在单击鼠标时会多次调用此代码段。为了避免这种情况,你可以做两件事。
在第一个解决方案中,您使用事件,因此仅在鼠标按钮的状态更改时添加形状(您还可以收听MouseButtonReleased
以模拟完全单击(:
if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Left)
{
// Hit Detection
}
}
或者第二个解决方案,你记得按钮的最后状态(可能在for循环之外进行一次鼠标检查(:
bool mouse_was_up = true;
if (mouse_was_up && Mouse::isButtonPressed(Mouse::Left)) {
mouse_was_up = false;
for (auto& it : onCanvas) {
// Hit Detection
}
}
else if (!Mouse::isButtonPressed(Mouse::Left))
mouse_was_up = true;
我宁愿坚持使用第一个解决方案,因为当您的点击太短并且您的游戏循环处于游戏逻辑的另一部分时,您可能会错过点击。
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- 如何通过 malloc 为队列数组分配内存?
- 具有动态数组分配的OpenMP嵌套循环
- 如何为数组结构的数组分配内存
- 如何为结构数组分配内存?
- cpp 数组 - 分配常量索引有效,而非常量索引不起作用
- 如何为字符指针数组分配内存?
- 在 C++ 中初始化后的数组分配
- 将数据分配给了数组分配,但程序显示了以缓冲区超支的输出
- C++函数问题中的数组分配
- 子数组分配:使用聚合对象错误的预期"{...}"进行初始化
- 为什么我的指针数组分配不起作用
- std::堆栈和堆栈溢出错误的数组分配
- 在 c++ 中是否有通过声明"implicit"数组分配?
- 在 c++ 中为 2-D "Dynamically Created"数组分配值时遇到问题
- 如何为C++数组分配指向第一个元素的指针
- 字符数组分配
- 将数组分配在固定数量的线程之间
- 为构造函数中的数组分配值