Important: Please read the Qt Code of Conduct -

Can't shoot bullets from the tip of the turret after calling setRotation()

  • 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 0_1502829442029_greenTower.png
    Also, the bullet looks like this 0_1502829474028_blueBullet.png
    What I want to do is make the turret shot the bullet to a certain point (for example [code]attackDestination = QPointF(1000, 500);[/code]

    for this, I have a class Bullet, with the slot move, 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();
    this->setRotation(90 + angle);


    I 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)


    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 ?

  • Sorry, my English is poor.
    I think in your class Bullet, the construtor should be like this:

    Bullet(qreal  rotateAngel)

    so, when you construct a bullet object, it already have the right angle to go forwards, and , the Tower , once the tower fire a bullet, it
    shold not have the right to control bullet.

    I guess the reason is this:


    does not equals :

    Bullet(qreal  rotateAngel)

    because the two rotation function are not base on the same translate system.

    well... let me have try..

  • you can try this :

    a little game, almost the same with yours. not finished yet.

    use keys: w , s , a , d to move the tank and mouse to control the turrent direction, and mouse's left button click to fire a bullet.
    mouse's right button pressed for locking the turrent direction.