Evgenii Legotckoi
Sept. 22, 2015, 10:36 p.m.

How to make game using Qt - Lesson 4. Enemy – meaning in the survival

Continuing the theme of how to write a play on Qt. Once in past articles a fly was created, that eating apples, it is time to create her enemy. And the enemy flies, as is well known, the spider. Creation of game characters, who will participate in the immediate life of your main character - is not only rendering the animation action and movement, as well as the reactions of the logic on the impact of the player, but also artificial intelligence, in accordance with the logic of which will be determined by the behavior of the game character. Thus, we add to the game a new meaning, not only to eat as many apples, but to survive at any cost.

We define the behavior of the spider in this game. What should he do? Yes, the most common of all the action - to hunt a fly just chasing it on the playing field.

Also add to the game button to start the game process, and pause, and the most important thing to add - it's Game Over.

The enemy flies in the project structure

As is the case with the fly in the structure of the project added an additional class, which will be responsible for the object, which is a spider.

  • spider.h - header file of spider
  • spider.cpp - source file of spider

spider.h

The difference between this file from the file header flies is that it declared the game timer, which is responsible for the behavior of the Spider, the enemy of Flies is clocked by its own internal clock. Also during initialization spider lays its purpose in him, that is, fly, for which he should be relentless. In this case, the artificial intelligence is primitive to ugliness, but more at the moment and is not required.

  1. #ifndef SPIDER_H
  2. #define SPIDER_H
  3.  
  4. #include <QObject>
  5. #include <QGraphicsItem>
  6. #include <QGraphicsScene>
  7. #include <QPainter>
  8. #include <QTimer>
  9. #include <QDebug>
  10.  
  11. class Spider : public QObject, public QGraphicsItem
  12. {
  13. Q_OBJECT
  14. public:
  15. explicit Spider(QGraphicsItem * target, QObject *parent = 0);
  16. ~Spider();
  17. void pause(); // Init of pause
  18.  
  19. signals:
  20. void signalCheckGameOver(); // Game Over signal
  21.  
  22. public slots:
  23.  
  24. protected:
  25. QRectF boundingRect() const;
  26. void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
  27.  
  28. private:
  29. qreal angle; // The angle of rotation of the graphic object
  30. int steps; // Number position spider legs
  31. int countForSteps; // Counter to change the position of the legs
  32. QTimer *timer; // Internal timer of spider
  33. QGraphicsItem * target; // The purpose of the spider, this object is equal Flies object
  34.  
  35. private slots:
  36. void slotGameTimer(); // Slot of game timer
  37. };
  38.  
  39. #endif // SPIDER_H

spider.cpp

The source code of Spider is similar to source code of Flies, with the difference that in the player slots Spider follow of Flies on the board, and spider turns to the side and flies crawling on her. And as soon as the enemy flies stumbles on some of the objects on the graphic scene, then checks whether the object Mucha, if so, what procedure is initialized Game Over.

  1. #include "spider.h"
  2. #include "math.h"
  3.  
  4. static const double Pi = 3.14159265358979323846264338327950288419717;
  5. static double TwoPi = 2.0 * Pi;
  6.  
  7. static qreal normalizeAngle(qreal angle)
  8. {
  9. while (angle < 0)
  10. angle += TwoPi;
  11. while (angle > TwoPi)
  12. angle -= TwoPi;
  13. return angle;
  14. }
  15.  
  16. Spider::Spider(QGraphicsItem *target, QObject *parent) :
  17. QObject(parent), QGraphicsItem()
  18. {
  19. angle = 0;
  20. steps = 0;
  21. countForSteps = 0;
  22. setRotation(angle); // Set the angle of rotation of the graphic object
  23.  
  24. this->target = target; // We set the goal of spider
  25.  
  26. timer = new QTimer();
  27. connect(timer, &QTimer::timeout, this, &Spider::slotGameTimer);
  28. timer->start(15); // Запускаем таймер
  29. }
  30.  
  31. Spider::~Spider()
  32. {
  33.  
  34. }
  35.  
  36. QRectF Spider::boundingRect() const
  37. {
  38. return QRectF(-40,-50,80,100);
  39. }
  40.  
  41. void Spider::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
  42. {
  43. painter->setPen(QPen(Qt::black, 2));
  44. if(steps == 0){ // The first position of the legs
  45. // Left 1
  46. painter->drawLine(-24,-45,-28,-35);
  47. painter->drawLine(-28,-35,-22,-10);
  48. painter->drawLine(-22,-10,0,0);
  49. // Right 1
  50. painter->drawLine(24,-45,28,-35);
  51. painter->drawLine(28,-35,22,-10);
  52. painter->drawLine(22,-10,0,0);
  53.  
  54. // Left 2
  55. painter->drawLine(-35,-38,-30,-18);
  56. painter->drawLine(-30,-18,-25,-3);
  57. painter->drawLine(-25,-3,0,0);
  58. // Right 2
  59. painter->drawLine(35,-38,30,-18);
  60. painter->drawLine(30,-18,25,-3);
  61. painter->drawLine(25,-3,0,0);
  62.  
  63. // Left 3
  64. painter->drawLine(-35,38,-30,18);
  65. painter->drawLine(-30,18,-25,3);
  66. painter->drawLine(-25,3,0,0);
  67. // Right 3
  68. painter->drawLine(35,38,30,18);
  69. painter->drawLine(30,18,25,3);
  70. painter->drawLine(25,3,0,0);
  71.  
  72. // Left 4
  73. painter->drawLine(-24,45,-28,35);
  74. painter->drawLine(-28,35,-22,10);
  75. painter->drawLine(-22,10,0,0);
  76. // Right 4
  77. painter->drawLine(24,45,28,35);
  78. painter->drawLine(28,35,22,10);
  79. painter->drawLine(22,10,0,0);
  80. } else if (steps == 1){ // The second position of the legs
  81. // Left 1
  82. painter->drawLine(-23,-40,-24,-30);
  83. painter->drawLine(-24,-30,-19,-9);
  84. painter->drawLine(-19,-9,0,0);
  85. // Right 1
  86. painter->drawLine(20,-50,23,-40);
  87. painter->drawLine(23,-40,15,-12);
  88. painter->drawLine(15,-12,0,0);
  89.  
  90. // Left 2
  91. painter->drawLine(-30,-35,-27,-24);
  92. painter->drawLine(-27,-24,-23,-5);
  93. painter->drawLine(-23,-5,0,0);
  94. // Right 2
  95. painter->drawLine(40,-27,35,-10);
  96. painter->drawLine(35,-10,28,-1);
  97. painter->drawLine(28,-1,0,0);
  98.  
  99. // Left 3
  100. painter->drawLine(-40,27,-35,10);
  101. painter->drawLine(-35,10,-28,1);
  102. painter->drawLine(-28,1,0,0);
  103. // Right 3
  104. painter->drawLine(30,35,27,24);
  105. painter->drawLine(27,24,23,5);
  106. painter->drawLine(23,5,0,0);
  107.  
  108. // Left 4
  109. painter->drawLine(-20,50,-27,30);
  110. painter->drawLine(-27,30,-20,12);
  111. painter->drawLine(-20,12,0,0);
  112. // Right 4
  113. painter->drawLine(23,40,24,30);
  114. painter->drawLine(24,30,19,9);
  115. painter->drawLine(19,9,0,0);
  116. } else if (steps == 2){ // The third position of the legs
  117. // Left 1
  118. painter->drawLine(-20,-50,-23,-40);
  119. painter->drawLine(-23,-40,-15,-12);
  120. painter->drawLine(-15,-12,0,0);
  121. // Right 1
  122. painter->drawLine(23,-40,24,-30);
  123. painter->drawLine(24,-30,19,-9);
  124. painter->drawLine(19,-9,0,0);
  125.  
  126. // Left 2
  127. painter->drawLine(-40,-27,-35,-10);
  128. painter->drawLine(-35,-10,-28,-1);
  129. painter->drawLine(-28,-1,0,0);
  130. // Right 2
  131. painter->drawLine(30,-35,27,-24);
  132. painter->drawLine(27,-24,23,-5);
  133. painter->drawLine(23,-5,0,0);
  134.  
  135. // Left 3
  136. painter->drawLine(-30,35,-27,24);
  137. painter->drawLine(-27,24,-23,5);
  138. painter->drawLine(-23,5,0,0);
  139. // Right 3
  140. painter->drawLine(40,27,35,10);
  141. painter->drawLine(35,10,28,1);
  142. painter->drawLine(28,1,0,0);
  143.  
  144. // Left 4
  145. painter->drawLine(-23,40,-24,30);
  146. painter->drawLine(-24,30,-19,9);
  147. painter->drawLine(-19,9,0,0);
  148. // Right 4
  149. painter->drawLine(20,50,27,30);
  150. painter->drawLine(27,30,20,12);
  151. painter->drawLine(20,12,0,0);
  152. }
  153.  
  154. painter->setPen(QPen(Qt::black, 1));
  155. // The left mandibles
  156. QPainterPath path1(QPointF(0, -20));
  157. path1.cubicTo(0, -20, -5, -25, -3, -35);
  158. path1.cubicTo(-3,-35,-15,-25,-8,-17);
  159. path1.cubicTo(-8,-17,-5,15,0,-20 );
  160. painter->setBrush(Qt::black);
  161. painter->drawPath(path1);
  162.  
  163. // The right mandibles
  164. QPainterPath path2(QPointF(0, -20));
  165. path2.cubicTo(0, -20, 5, -25, 3, -35);
  166. path2.cubicTo(3,-35,15,-25,8,-17);
  167. path2.cubicTo(8,-17,5,15,0,-20 );
  168. painter->setBrush(Qt::black);
  169. painter->drawPath(path2);
  170.  
  171. // head
  172. painter->setBrush(QColor(146, 115, 40, 255));
  173. painter->drawEllipse(-10,-25,20,15);
  174. // Body
  175. painter->drawEllipse(-15, -15, 30, 30);
  176. // Back
  177. painter->drawEllipse(-20, 0, 40,50);
  178. painter->setPen(QPen(Qt::white,3));
  179. painter->drawLine(-10,25,10,25);
  180. painter->drawLine(0,35,0,15);
  181. // Left eye
  182. painter->setPen(QPen(Qt::black,1));
  183. painter->setBrush(Qt::red);
  184. painter->drawEllipse(-8,-23,6,8);
  185. // Right eye
  186. painter->setBrush(Qt::red);
  187. painter->drawEllipse(2,-23,6,8);
  188.  
  189. Q_UNUSED(option);
  190. Q_UNUSED(widget);
  191. }
  192.  
  193. void Spider::slotGameTimer()
  194. {
  195. // Determine the distance to Fly
  196. QLineF lineToTarget(QPointF(0, 0), mapFromItem(target, 0, 0));
  197. // The angle of rotation in the direction of Fly
  198. qreal angleToTarget = ::acos(lineToTarget.dx() / lineToTarget.length());
  199. if (lineToTarget.dy() < 0)
  200. angleToTarget = TwoPi - angleToTarget;
  201. angleToTarget = normalizeAngle((Pi - angleToTarget) + Pi / 2);
  202.  
  203. /* Depending on whether the left or the right is from the Fly spider,
  204.   * set the direction of rotation of the spider in the timer tick.
  205.   * The speed of rotation depends on the angle at which you must turn the spider
  206. * */
  207. if (angleToTarget > 0 && angleToTarget < Pi) {
  208. // Rotate left
  209. if(angleToTarget > Pi / 5){
  210. angle = -15;
  211. } else if(angleToTarget > Pi / 10){
  212. angle = -5;
  213. } else {
  214. angle = -1;
  215. }
  216. } else if (angleToTarget <= TwoPi && angleToTarget > (TwoPi - Pi)) {
  217. // Rotate right
  218. if(angleToTarget < (TwoPi - Pi / 5)){
  219. angle = 15;
  220. } else if(angleToTarget < (TwoPi - Pi / 10)){
  221. angle = 5;
  222. } else {
  223. angle = 1;
  224. }
  225. } else if(angleToTarget == 0) {
  226. angle = 0;
  227. }
  228.  
  229. setRotation(rotation() + angle); // Turned
  230.  
  231. // Бежим в сторону мухи
  232. if(lineToTarget.length() >= 40){
  233. setPos(mapToParent(0, -(qrand() % ((4 + 1) - 1) + 1)));
  234.  
  235. countForSteps++;
  236. if(countForSteps == 6){
  237. steps = 1;
  238. update(QRectF(-40,-50,80,100));
  239. } else if (countForSteps == 12){
  240. steps = 0;
  241. update(QRectF(-40,-50,80,100));
  242. } else if (countForSteps == 18){
  243. steps = 2;
  244. update(QRectF(-40,-50,80,100));
  245. } else if (countForSteps == 24) {
  246. steps = 0;
  247. update(QRectF(-40,-50,80,100));
  248. countForSteps = 0;
  249. }
  250. }
  251.  
  252. /* Checks for whether the spider came on any element in the graphic scene.
  253. * */
  254. QList<QGraphicsItem *> foundItems = scene()->items(QPolygonF()
  255. << mapToScene(0, 0)
  256. << mapToScene(-2, -2)
  257. << mapToScene(2, -2));
  258. /* Check elements. Try to find fly
  259. * */
  260. foreach (QGraphicsItem *item, foundItems) {
  261. if (item == this)
  262. continue;
  263. if(item == target){
  264. emit signalCheckGameOver();
  265. }
  266. }
  267.  
  268. /* Check the output of the field boundary
  269.      * If the subject is beyond the set boundaries, then return it back
  270. * */
  271. if(this->x() - 10 < -250){
  272. this->setX(-240); // left
  273. }
  274. if(this->x() + 10 > 250){
  275. this->setX(240); // right
  276. }
  277.  
  278. if(this->y() - 10 < -250){
  279. this->setY(-240); // top
  280. }
  281. if(this->y() + 10 > 250){
  282. this->setY(240); // bottom
  283. }
  284. }
  285.  
  286. /* Pause function, is responsible for enabling and disabling the pause
  287. * */
  288. void Spider::pause()
  289. {
  290. if(timer->isActive()){
  291. timer->stop();
  292. } else {
  293. timer->start(15);
  294. }
  295. }

widget.h

In the header file, the application kernel to determine the object, which is responsible for the Spider, the variable of the game state,  Pause Hot Key. And a slot for the processing start of the game, pause and Game Over procedures.

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5. #include <QGraphicsScene>
  6. #include <QGraphicsItem>
  7. #include <QShortcut>
  8. #include <QDebug>
  9. #include <QTimer>
  10. #include <QMessageBox>
  11.  
  12. #include <triangle.h>
  13. #include <apple.h>
  14. #include <spider.h>
  15.  
  16. #define GAME_STOPED 0
  17. #define GAME_STARTED 1
  18.  
  19. namespace Ui {
  20. class Widget;
  21. }
  22.  
  23. class Widget : public QWidget
  24. {
  25. Q_OBJECT
  26.  
  27. public:
  28. explicit Widget(QWidget *parent = 0);
  29. ~Widget();
  30.  
  31. private:
  32. Ui::Widget *ui;
  33. QGraphicsScene *scene;
  34. Triangle *triangle;
  35. QTimer *timer; // Game Timer
  36. QTimer *timerCreateApple; /// Timer for periodic
  37.  
  38. QList<QGraphicsItem *> apples; /// List with all apples
  39. double count; /// Scores
  40.  
  41. Spider *spider;
  42.  
  43. QShortcut *pauseKey; // Pause hot key
  44. int gameState;
  45.  
  46. private slots:
  47. /// The slot for the removal of apples if fly stumbled upon this apple
  48. void slotDeleteApple(QGraphicsItem * item);
  49. void slotCreateApple(); /// The slot for the creation of apples, triggered by a timer
  50.  
  51. void on_pushButton_clicked(); // The slot for the start of the game
  52. void slotGameOver(); // Slot of Game Over
  53. void slotPause(); // Slot of Pause
  54. };
  55.  
  56. #endif // WIDGET_H

widget.cpp

Compared with the program code that has been in previous lessons, with the file in this tutorial, you need to thoroughly work. As the game starts by pressing pushButton button, and the program code object initialization and launch timers need to make in the slot, which is transmitted from the signal button. Also, there is a need to implement a pause function in the game, in which all the game timer is stopped and can not move objects or perform other actions. And in the slot, which is responsible for the Game Over is necessary to properly handle the deletion of all objects with the gaming scene.

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3.  
  4. Widget::Widget(QWidget *parent) :
  5. QWidget(parent),
  6. ui(new Ui::Widget)
  7. {
  8. ui->setupUi(this);
  9. this->resize(600,640);
  10. this->setFixedSize(600,640);
  11.  
  12. scene = new QGraphicsScene();
  13.  
  14. ui->graphicsView->setScene(scene);
  15. ui->graphicsView->setRenderHint(QPainter::Antialiasing);
  16. ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  17. ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  18.  
  19. scene->setSceneRect(-250,-250,500,500);
  20. timer = new QTimer();
  21. timerCreateApple = new QTimer();
  22.  
  23. gameState = GAME_STOPED;
  24.  
  25. pauseKey = new QShortcut(this);
  26. pauseKey->setKey(Qt::Key_Pause);
  27. connect(pauseKey, &QShortcut::activated, this, &Widget::slotPause);
  28.  
  29.  
  30. }
  31.  
  32. Widget::~Widget()
  33. {
  34. delete ui;
  35. }
  36.  
  37. void Widget::slotDeleteApple(QGraphicsItem *item)
  38. {
  39. foreach (QGraphicsItem *apple, apples) {
  40. if(apple == item){
  41. scene->removeItem(apple);
  42. apples.removeOne(apple);
  43. delete apple;
  44. ui->lcdNumber->display(count++);
  45. }
  46. }
  47. }
  48.  
  49. void Widget::slotCreateApple()
  50. {
  51. Apple *apple = new Apple();
  52. scene->addItem(apple);
  53. apple->setPos((qrand() % (251)) * ((qrand()%2 == 1)?1:-1),
  54. (qrand() % (251)) * ((qrand()%2 == 1)?1:-1));
  55. apple->setZValue(-1);
  56. apples.append(apple);
  57. }
  58.  
  59. void Widget::on_pushButton_clicked()
  60. {
  61. count = 0;
  62. ui->lcdNumber->display(count);
  63. triangle = new Triangle();
  64.  
  65. scene->addItem(triangle);
  66. triangle->setPos(0,0);
  67.  
  68. spider = new Spider(triangle); // Init Spider
  69. scene->addItem(spider); // Add Spider to scene
  70. spider->setPos(180,180); // Set Spider position
  71.  
  72. connect(spider, &Spider::signalCheckGameOver, this, &Widget::slotGameOver);
  73.  
  74. connect(timer, &QTimer::timeout, triangle, &Triangle::slotGameTimer);
  75. timer->start(1000 / 100);
  76.  
  77. connect(timerCreateApple, &QTimer::timeout, this, &Widget::slotCreateApple);
  78. timerCreateApple->start(1000);
  79.  
  80. connect(triangle, &Triangle::signalCheckItem, this, &Widget::slotDeleteApple);
  81.  
  82. ui->pushButton->setEnabled(false);
  83.  
  84. gameState = GAME_STARTED;
  85. }
  86.  
  87. void Widget::slotGameOver()
  88. {
  89. /* If Game Over, then disable timers
  90. * */
  91. timer->stop();
  92. timerCreateApple->stop();
  93. QMessageBox::warning(this,
  94. "Game Over",
  95. "Мои соболезнования, но Вас только что слопали");
  96. /* Отключаем все сигналы от слотов
  97. * */
  98. disconnect(timerCreateApple, &QTimer::timeout, this, &Widget::slotCreateApple);
  99. disconnect(triangle, &Triangle::signalCheckItem, this, &Widget::slotDeleteApple);
  100. disconnect(spider, &Spider::signalCheckGameOver, this, &Widget::slotGameOver);
  101. /* И удаляем все объекты со сцены
  102. * */
  103. spider->deleteLater();
  104. triangle->deleteLater();
  105.  
  106. foreach (QGraphicsItem *apple, apples) {
  107. scene->removeItem(apple);
  108. apples.removeOne(apple);
  109. delete apple;
  110. }
  111.  
  112. ui->pushButton->setEnabled(true);
  113.  
  114. gameState = GAME_STOPED;
  115. }
  116.  
  117. void Widget::slotPause()
  118. {
  119. if(gameState == GAME_STARTED){
  120. if(timer->isActive()){
  121. timer->stop();
  122. timerCreateApple->stop();
  123. spider->pause();
  124. } else {
  125. timer->start(1000/100);
  126. timerCreateApple->start(1000);
  127. spider->pause();
  128. }
  129. }
  130. }

Result

According to the results of the work ceases to be a game of infinite value of scores will increase at times.

A full list of articles in this series:

Video

Do you like it? Share on social networks!

v
  • May 9, 2017, 7:27 p.m.

Здравствуй у меня опять проблема как решить? In member function 'void Widget::on_pushButton_clicked()': ошибка: 'class Ui::Widget' has no member named 'pushButton' ui->pushButton->setEnabled(false); : In member function 'void Widget::slotGameOver()': ошибка: 'class Ui::Widget' has no member named 'pushButton' ui->pushButton->setEnabled(true); скрин http://priscree.ru/img/a9de07f8d2a5a0.jpg ^ ^

v
  • May 9, 2017, 7:46 p.m.

вставляю кнопку вообще 10 ошибок не определена ссылка на паука и тд

Evgenii Legotckoi
  • May 10, 2017, 12:06 p.m.

Добавьте через графический дизайнер кнопку в widget.ui и проследите, чтобы название кнопки было pushButton

v
  • May 10, 2017, 2:40 p.m.

добавил кнопку все равно много ошибок вот скрины http://priscree.ru/img/e8e0d04f9e232c.jpg http://priscree.ru/img/3fb040824e8665.jpg

Evgenii Legotckoi
  • May 10, 2017, 3:21 p.m.

ошибки в vtable... Это moc файлы попортились. Нужно удалить build сборку и пересобрать, и если не поможет, то создать новый проект и переписать в него код. Иначе никак.

v
  • May 10, 2017, 5 p.m.

хорошо попробую переписать все.как напишу отпишусь)

v
  • May 10, 2017, 6:58 p.m.

все заработало спасибо еще вопрос у нас препод просит чтобы мы сделали так.чтобы можно было сохранять результаты это возможно ?

Evgenii Legotckoi
  • May 10, 2017, 7:20 p.m.

Конечно, возможно. Можно сохранять в файл. Можно сохранять в базу данных. Можно даже в реестр писать с помощью QSettings . Мне больше всего нравится база данных для таких целей. По окончании игры можно добавлять результат в базу данных. Также можно добавить кнопку, которая бы открывала окно с результатами.

v
  • May 10, 2017, 7:46 p.m.

а как это сделать ? можете помочь если не сложно конечно и есть время

Evgenii Legotckoi
  • May 10, 2017, 8:46 p.m.

Значит так. Просто писать код за вас я не буду, но подсказать и направить на нужный путь - это без проблем.

Поэтому -> В предыдущем сообщении я дал ссылку на статью с базой данных. Изучите её. Изучите, как добавлять записи в базу данных. Там же показано, как отобразить записи в таблице. А потом попытайтесь по окончании игры сделать добавление строк в базу данных. В коде есть место, где по окончании игры вызывается диалог. Это происходит в слоте slotGameOver . Вот в нём можно сделать добавление записей в базу данных. Также можете добавить кнопку в окно игры, по нажатию которой можно будет вызвать диалог, в котором как раз и будете показывать рекорды. Если есть затруднения с пониманием сигналов и слотов, то изучите следующую статью .

M
  • June 25, 2018, 3:13 p.m.

Здравствуйте,
Подскажите, пжлст, как работает этот код :

  1. QLineF lineToTarget(QPointF(0, 0), mapFromItem(target, 0, 0));  // Проводим линию от паука к мухе
  2. qreal angleToTarget = ::acos(lineToTarget.dx() / lineToTarget.length()); // Находим угол. Например 120 гр( 2пи/3 )
  3. if (lineToTarget.dy() < 0)                                             //Если y отрицательный зачем отнимать?
  4. angleToTarget = TwoPi - angleToTarget;                 // ??
  5. angleToTarget = normalizeAngle((Pi - angleToTarget) + Pi / 2); // Тут мы убираем намотку по 2пи. Но зачем добавлять 90 гр?
    Самое непонятное - это 5 -ая строчка, зачем добавлять 90 градусов?

M
  • June 25, 2018, 3:25 p.m.

не 90 на 45, ошибся

Evgenii Legotckoi
  • June 25, 2018, 3:34 p.m.

Там неправильный подсчёт был по направлению и полный бардак был с поведением, эти 45 градусов исправляли ситуацию. Точную причину уже совсем не помню.

А вообще все эти расчёты довольно тяжелы для процессора, я подобрал более лёгкий вариант со скалярными векторами. Но статью ещё пока не недописал к сожалению (она пока в разработке).

РР
  • June 4, 2019, 9:28 p.m.
  • (edited)

Здравствуйте! Почему может быть такая ошибка: враг висит в углу, колеблется в нём, но не двигается? По логике код такой же, но вместо орисовки моделей использую спрайты. Со спрайтом "мухи" всё хорошо, а вот "паук" отказывается вести себя нормально. Подозреваю, что ошибка может быть здесь (это код, который идёт вместо отрисовки):

  1. void Crocodillo::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
  2. {
  3. painter->drawPixmap(-10,-10, *spriteImageCroco, currentFrameCroco, 0, 96,95);
  4. Q_UNUSED(option);
  5. Q_UNUSED(widget);
  6. }

Или же ошибка где-то в управлении "паука", но там код вообще неизменный. (в Spider.cpp, void Spider...)

Evgenii Legotckoi
  • June 5, 2019, 1:44 p.m.

Добрый день.

Дело тут явно не в методе paint, скорее всего всё-таки есть какая-то ошибка в другом месте. Обычно такое может быть в районе метода slotGamerTimer

РР
  • June 6, 2019, 6:27 a.m.
  • (edited)

Спасибо! На самом деле ошибка оказалась от невнимательности - просто пропустила подключение движения в сторону модели. Теперь всё работает.

Если вам не сложно, могли бы вы, пожалуйста, объяснить, за что отвечают параметры в скобках тут: setPos(mapToParent(0, -(qrand() % ((2 + 1) - 1) + 1)))?
Нашла только такое, не много о чём говорит: (qrand() % ((high + 1) - low) + low). Экспериментально кое-что выяснила, но хотелось бы знать точно)
А ещё вот тут, когда генерировали бананы: banana->setPos((qrand() % (251)) * ((qrand()%2 == 1)?1:-1),
(qrand() % (251)) * ((qrand()%2 == 1)?1:-1));

А так, благодарю за указку на slotGameTimer!

П.С.: я не очень умею пока читать документацию( поэтому прошу помощи у вас, чтобы разобраться с этими параметрами

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup