0

我正在使用图形视图框架在 Qt 中开发 RPG 游戏。我创建了一个类“Player”,它继承了 QGraphicsItem。现在,我正在尝试制作一个“攻击”动画,所以每次我按空格键时,角色前面都会有一个动画。我已经使用“advance()”函数实现了移动动画。

因此,每次我按空格键时,“is_attacking”变量都会变为真。每 85 毫秒,程序检查“is_attacking”是否为真,如果是,动画将前进(绘制下一帧)并更新。当所有帧都被使用时,“is_attacking”变为假。

问题是我不能使用“播放器”类来绘制动画。QGraphicsItem 是独立的,有自己的坐标系。我已经完成了攻击系统,但我无法将动画绘制到场景中。

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

     }


   } 

}

我如何使用 QGraphicsItem 中的“paint()”来绘制该项目所属的 QGraphicsScene?

4

1 回答 1

0

paint()用于以局部坐标绘制项目。更改项目位置所需的setPos()功能是设置项目在父坐标中的位置。

动画不应在paint()函数中处理(除非您想更改项目的位置),而是在计时器超时时调用的插槽中处理:

// 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;
     }
   }
}

请注意,为了启用信号/插槽,您应该继承自QGraphicsObject而不是QGraphicsItem.

于 2012-11-25T12:49:54.700 回答