如何将到达图形视图右侧(末端)的QGraphicsPixmapItem移动到左侧(开始)侧(就像在贪吃蛇游戏中发生的事情
How can I move a QGraphicsPixmapItem that reachs the right (end) of graphicView to the left (begining) side(like what is happening in the snake game)
我有一个QGraphicsView小部件,它显示一个像素图项目。用户可以移动项目。当项目到达图形视图的右端(或左端(时,我希望项目从另一端进入(具有相同的 X 和 Y 协调(就像在贪吃蛇游戏中发生的情况一样(
解决方案
设置像素图的位置时,检查它是否小于场景矩形的宽度-像素图的宽度,如果not
,则将位置设置为zero
。
注意:如果向相反方向移动,请执行类似的检查,即将像素图的位置设置为场景矩形的宽度- 像素图的宽度,如果它不大于像素图的宽度。
例
以下是我为您准备的一个最小示例,以演示如何实施建议的解决方案:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QPixmap pixmap(64, 64);
auto *view = new QGraphicsView(this);
auto *item = new QGraphicsPixmapItem(pixmap);
auto *animation = new QVariantAnimation(this);
view->setScene(new QGraphicsScene(this));
view->setAlignment(Qt::AlignLeft | Qt::AlignTop);
view->setSceneRect(0, 0, 300, 200);
view->scene()->addItem(item);
setCentralWidget(view);
resize(302, 202);
connect(animation, &QVariantAnimation::valueChanged, [view, item](){
int x = item->x();
if (x < (view->sceneRect().width() - item->pixmap().width()))
item->setX(x + 1);
else
item->setX(0);
});
animation->setStartValue(0);
animation->setEndValue(1000);
animation->setDuration(10000);
animation->start();
}
我准备的更全面的贪吃蛇游戏示例的代码可在 GitHub 上找到。
相关文章:
- 将对象移动到std::shared_ptr
- 何时在引用或唯一指针上使用移动语义
- 如何将到达图形视图右侧(末端)的QGraphicsPixmapItem移动到左侧(开始)侧(就像在贪吃蛇游戏中发生的事情
- 在我的小行星游戏中,我无法在x坐标上移动我的飞船
- 在C++中,我的主机游戏角色在游戏场数组内移动时不会停止
- 如何在Unreal Engine 4移动游戏开发C 中接受接触式拖盘活动
- C++中的贪吃蛇游戏:蛇头没有按预期移动
- 我不能在不使用指针的情况下返回 2d 数组!我正在制作一个井字游戏类型游戏,这是我的向上移动功能
- 按下按键或移动鼠标时,游戏速度会减慢
- 允许用户在迷宫游戏中最多移动五个空间
- 为什么我的TicTacToe游戏在生成随机移动时会卡住
- 游戏引擎中的移动如何工作
- 有人能建议我如何在网格游戏中移动士兵时解决一个牢房中的旁路问题吗
- 制作贪吃蛇游戏。检测到移动后,我无法更改屏幕。C++
- SDL 在游戏中更流畅地移动
- 汽车在我的游戏中无法正确移动 C++
- 改进Snake游戏的移动设计
- 在cocos2d-x中的游戏场景中随机移动障碍物
- C++ DirectX11 2d 游戏:阻止敌人精灵相互移动
- 在FPS游戏中使用鼠标输入时,移动速度出乎意料地加快