PDA

View Full Version : How to find pos relative to QPixMapItem after rotation



octacore
15th August 2017, 21:29
I am working on a tower defence game and trying to shoot a projectile from a turret. The sprite of the turret I have looks like this :12552
Also, the bullet looks like this 12553
What I want to do is make the turret shot the bullet to a certain point (for example attackDestination = QPointF(1000, 500);)

For this, I have a class Bullet, with the slot move, which is connected to a QTimer:


void Bullet::move()
{

int stepSize = 20; // how fast the bullet moves
double angle = rotation();

double dy = stepSize * qSin(qDegreesToRadians(angle)); // The X that needs to be moved
double dx = stepSize * qCos(qDegreesToRadians(angle)); // The Y that needs to be moved

setPos(x() + dx, y() + dy);
}

I also have a slot in the Tower class (which stands for the turret)

void Tower::attackTarget()
{
Bullet *bullet = new Bullet();
//getWidthMap() returns the width of the tower
//getHeightMap() returns the height of the tower

bullet->setPos(x() + getWidthMap() /2, y());

QLineF line(QPointF(x() + getWidthMap() /2, y()), attackDestination);
double angle =(-1) * line.angle();

bullet->setRotation(angle);

this->setRotation(90 + angle);

game->scene->addItem(bullet);

}

have rotated the turret by +90 degrees because its initial position is vertical and it needs to form an angle (that of the line with oX) just like the bullet. The rotation happens clockwise.
The problem is with the position of the bullet relative to the turret when attacking.

Without the line this->setRotation(90 + angle); (first picture), with it (second picture)

12550
12551

As you can see, the bullets are starting from the initial position of the turret (when it was not rotated), because the pos() function keeps the initial X and Y. How can I fix that so the bullet is always shooting from the turret?

high_flyer
15th August 2017, 21:40
It was long time ago since I have dealt with special painting, so I might not be 100% with this but as I remember, the default rotation axis is not the center of your object but its upper left corner (of the bounding box).
So what I think is happening is that your bullet is in the right position, but your turret is not (after turning), since it is not turning on its own axis but rather on the upper left corner of the turret bonding box.
You need to move the axis point to be in the middle of your object.
If you switch between the two screenshots back and forth you actually can see what I am talking about.