Qt C++ QGraphicsItem Changing position to (2x,2y) on advance() call

266 views Asked by At

QGraphicsItem Changing position to (2x,2y) on advance() call

The Problem

I have a class that extends QGraphicsItem, the object is displaying fine to the scene until I call advance() to animate the object. As soon as advance is called and the position is changed, the object immediately moves from (x,y) to (2x,2y). Here is my code for the object.

The Class

Zombie::Zombie(QRectF bounds, int refreshTime){

    speed = 5.0/1000*refreshTime;
    image = ":/assets/RegularZombie.png";
    x = bounds.x();
    y = bounds.y();
    width = bounds.width();
    height = bounds.height();

}

void Zombie::advance(int phase){

    if (!phase || eating) return;

    x = x-speed;

    //setPos(boundingRect().topLeft());
    setX(x);

}
QRectF Zombie::boundingRect() const{
    int x_pos = (int)x;
    return QRectF(x_pos,y,width,height);
}
void Zombie::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
    painter->drawImage(boundingRect(),QImage(image));
}

Upon creation, the object displays correctly at (x,y) however as soon as advance is called the object moves to (2x, 2y) and is animated from there.

I have another class structured similarly that is facing a similar issue.

As of now the only possible solution I have come up with is to divide the coordinates by 2 and set the position within the constructor however this still doesn't allow for any comparison with other objects on the scene (ex. contains).

Also, here is the code I use to add the object to the scene.

Calling Code

int column_width = scene->width()/WIDTH;
int column_height = scene->height()/HEIGHT;
int random = qrand()%HEIGHT;

QRectF rect(scene->width(),random*column_height,column_width,column_height);
zombies.append(new Zombie(rect,refreshRate));

scene->addItem(zombies.at(0));
cout<<rect3.x()<<endl;
cout<<zombies.at(0)->boundingRect().x()<<endl;

scene->update();

Thanks in advance for the help!

Ps. I'm not sure if this is relevant however it had me wondering, all of this is being processed on a Macbook Pro Retina

0

There are 0 answers