0

I am working on a RPG game in Qt, using the Graphics View Framework. I have create a class, "Player", which inherits QGraphicsItem. Now, i am trying to make an "attack" animation, so everytime i press the space key, there would be an animation in front of the character. I have already implemented the moving animation, using the "advance()" function.

So, every time i press space, the "is_attacking" variable becomes true. Every 85 miliseconds, the program checks if "is_attacking" is true, and if it is, the animation will advance(draw next frame) and update. When all frames have been used, "is_attacking" becomes false.

The problem is that i can't use the "Player" class to draw the animation. QGraphicsItem is independent and have it's own coordinate system. I've aleardy finished the attack system but i can't draw the animation onto the scene.

void Player::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){

painter->drawPixmap(QRect(0, 0, 32, 32), *pixmap, QRect(position.x(), position.y(), 32, 32));

if(its_attacking()){
    switch(pos){
case NORTH: // draw animation frame to x, y - 32
break;
case SOUTH: // draw animation frame to x, y + 32
break;
case WEST: // draw animation frame to x - 32, y
break;
case EAST: // draw animation frame to x + 32, y

     }


   } 

}

How could i use "paint()" from a QGraphicsItem to draw onto the QGraphicsScene which the item belongs to ?

Kanghu
  • 561
  • 1
  • 10
  • 23

1 Answers1

0

paint() is used in order to paint the item in local coordinates. What you need in order to change the item's position is the setPos() function which sets the item's position in parent's coordinates.

The animation should not be handled in the paint() function (except if you want to change item's position) but in the slot called at timer's timeout:

// Slot called at 85 ms timer's timeout
void Player::timerTimeoutSlot()
{
   if(its_attacking()){
      switch(pos){
        case NORTH: // draw animation frame to x, y - 32
            setPos(QPointF(pos().x(), pos().y()-32);
            break;
        case SOUTH: // draw animation frame to x, y + 32
            setPos(QPointF(pos().x(), pos().y()+32);
            break;
        case WEST: // draw animation frame to x - 32, y
            setPos(QPointF(pos().x()-32, pos().y());
            break;
        case EAST: // draw animation frame to x + 32, y
            setPos(QPointF(pos().x()+32, pos().y());
            break;
     }
   }
}

Notice that in order to enable signals/slots you should inherit from QGraphicsObject instead of QGraphicsItem.

pnezis
  • 12,023
  • 2
  • 38
  • 38