Home

Qt Tutorial - Chapter 11: Giving It a Shot

Screenshot of tutorial eleven

In this example we introduce a timer to implement animated shooting.

Line-by-line Walkthrough

t11/cannon.rb

The CannonField now has shooting capabilities.

Calling this slot will make the cannon shoot if a shot is not in the air.

    slots 'moveShot()'

This private slot is used to move the shot while it is in the air, using a Qt::Timer.

    @timerCount
    @autoShootTimer
    @shoot_ang
    @shoot_f

These instance variables contain information that describes the shot. The @timerCount keeps track of the time passed since the shot was fired. The @shoot_ang is the cannon angle and @shoot_f is the cannon force when the shot was fired.

    include Math

We include the math namespace because we need the sin() and cos() methods.

    def initialize(parent, name)
        super
        @ang = 45
        @f = 0
        @timerCount = 0;
        @autoShootTimer = Qt::Timer.new( self, "movement handler" )
        connect( @autoShootTimer, SIGNAL('timeout()'),
                 this, SLOT('moveShot()') )
        @shoot_ang = 0
        @shoot_f = 0
        setPalette( Qt::Palette.new( Qt::Color.new( 250, 250, 200) ) )
    end

We initialize our new instance variables and connect the Qt::Timer.timeout() signal to our moveShot() slot. We'll move the shot every time the timer times out.

    def shoot()
        if @autoShootTimer.isActive() 
            return
        end
        @timerCount = 0
        @shoot_ang = @ang
        @shoot_f = @f
        @autoShootTimer.start( 50 )
    end

This method shoots a shot unless a shot is in the air. The @timerCount is reset to zero. The @shoot_ang and @shoot_f are set to the current cannon angle and force. Finally, we start the timer.

    def moveShot()
        r = Qt::Region.new( shotRect() )
        timerCount += 1

        shotR = shotRect()

        if shotR.() > width() || shotR.y() > height() 
            @autoShootTimer.stop()
        else
            r = r.unite( Qt::Region.new( shotR ) )
        end
        repaint( r )
    end

moveShot() is the slot that moves the shot, called every 50 milliseconds when the Qt::Timer fires.

Its tasks are to compute the new position, repaint the screen with the shot in the new position, and if necessary, stop the timer.

First we make a Qt::Region that holds the old shotRect(). A Qt::Region is capable of holding any sort of region, and we'll use it here to simplify the painting. ShotRect() returns the rectangle where the shot is now - it is explained in detail later.

Then we increment the @timerCount, which has the effect of moving the shot one step along its trajectory.

Next we fetch the new shot rectangle.

If the shot has moved beyond the right or bottom edge of the widget, we stop the timer or we add the new shotRect() to the Qt::Region.

Finally, we repaint the Qt::Region. This will send a single paint event for just the one or two rectangles that need updating.

    def paintEvent( e )
        updateR = e.rect()
        p = Qt::Painter.new( self )

        if updateR.intersects( cannonRect() ) 
            paintCannon( p )
        end
        if @autoShootTimer.isActive() &&
             updateR.intersects( shotRect() )
            paintShot( p )
        end
    end

The paint event method has been split in two since the previous chapter. Now we fetch the bounding rectangle of the region that needs painting, check whether it intersects either the cannon and/or the shot, and if necessary, call paintCannon() and/or paintShot().

    def paintShot( p )
        p.setBrush( black )
        p.setPen( NoPen )
        p.drawRect( shotRect() )
    end

This private method paints the shot by drawing a black filled rectangle.

We leave out the implementation of paintCannon(); it is the same as the paintEvent() from the previous chapter.

    def shotRect()
        gravity = 4.0

        time      = @timerCount / 4.0
        velocity  = @shoot_f
        radians   = @shoot_ang*3.14159265/180.0

        velx      = velocity*cos( radians )
        vely      = velocity*sin( radians )
        x0        = ( @barrelRect.right()  + 5.0 )*cos(radians)
        y0        = ( @barrelRect.right()  + 5.0 )*sin(radians)
        x         = x0 + velx*time
        y         = y0 + vely*time - 0.5*gravity*time*time

        r = Qt::Rect.new( 0, 0, 6, 6 );
        r.moveCenter( Qt::Point.new( x.round, height() - 1 - y.round ) )
        return r
    end

This method calculates the center point of the shot and returns the enclosing rectangle of the shot. It uses the initial cannon force and angle in addition to @timerCount, which increases as time passes.

The formula used is the classical Newtonian formula for frictionless movement in a gravity field. For simplicity, we've chosen to disregard any Einsteinian effects.

We calculate the center point in a coordinate system where y coordinates increase upward. After we have calculated the center point, we construct a Qt::Rect with size 6x6 and move its center point to the point calculated above. In the same operation we convert the point into the widget's coordinate system (see The Coordinate System).

Math.round() rounds a double to the closest integer.

t11/t11.rb

The only addition is the Shoot button.

        shoot = Qt::PushButton.new( "&Shoot", self, "shoot" )
        shoot.setFont( Qt::Font.new( "Times", 18, QFont::Bold ) )

In the constructor we create and set up the Shoot button exactly like we did with the Quit button. Note that the first argument to the constructor is the button text, and the third is the widget's name.

        connect( shoot, SIGNAL('clicked()'), cannonField, SLOT('shoot()') )

Connects the clicked() signal of the Shoot button to the shoot() slot of the CannonField.

Behavior

The cannon can shoot, but there's nothing to shoot at.

Exercises

Make the shot a filled circle. Hint: Qt::Painter.drawEllipse() may help.

Change the color of the cannon when a shot is in the air.

You're now ready for Chapter 12.

[Previous tutorial] [Next tutorial] [Main tutorial page]


Copyright © 2004 TrolltechTrademarks
Qt 3.3.3