Giving It a Shot

Overview

Line by Line Walkthrough

includeMath</code>We include '''<tt>Math</tt>''' because we need the '''<tt>sin()</tt>''' and '''<tt>cos()</tt>''' functions.<syntaxhighlight lang="ruby">@timerCount = 0@autoShootTimer = Qt::Timer.new(self)connect(@autoShootTimer, SIGNAL('timeout()'), self, SLOT('moveShot()'))@shootAngle = 0@shootForce = 0</code>We initialize our new private variables and connect the [http://doc.qt.nokia.com/latest/qtimer.html#timeout Qt::Timer::timeout()] signal to our '''<tt>moveShot()</tt>''' slot. We'll move the shot every time the timer times out.The '''<tt>timerCount</tt>''' keeps track of the time passed since the shot was fired. The '''<tt>shootAngle</tt>''' is the cannon angle and '''<tt>shootForce</tt>''' is the cannon force when the shot was fired.<syntaxhighlight lang="ruby">def shoot() if @autoShootTimer.isActive() return end; @timerCount = 0 @shootAngle = @currentAngle @shootForce = @currentForce @autoShootTimer.start(5)end</code>This function shoots a shot unless a shot is in the air. The '''<tt>timerCount</tt>''' is reset to zero. The '''<tt>shootAngle</tt>''' and '''<tt>shootForce</tt>''' variables are set to the current cannon angle and force. Finally, we start the timer.<syntaxhighlight lang="ruby">def moveShot() region = Qt::Region.new(shotRect()) @timerCount += 1 shotR = shotRect() if shotR.x() > width() || shotR.y() > height() @autoShootTimer.stop() else region = region.unite(Qt::Region.new(shotR)) end update(region)end</code>'''<tt>moveShot()</tt>'''istheslotthatmovestheshot,calledevery5millisecondswhenthe[http://doc.qt.nokia.com/latest/qtimer.htmlQt::Timer]fires.Itstasksaretocomputethenewposition,updatethescreenwiththeshotinthenewposition,andifnecessary,stopthetimer.Firstwemakea[http://doc.qt.nokia.com/latest/qregion.htmlQt::Region]thatholdstheold'''<tt>shotRect()</tt>'''.A[http://doc.qt.nokia.com/latest/qregion.htmlQt::Region]iscapableofholdinganysortofregion,andwe'll use it here to simplify the painting. '''<tt>shotRect()</tt>''' returns the rectangle where the shot is now. It is explained in detail later.Then we increment the '''<tt>timerCount</tt>''', 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 '''<tt>shotRect()</tt>''' to the [http://doc.qt.nokia.com/latest/qregion.htmlQt::Region].Finally,werepaintthe[http://doc.qt.nokia.com/latest/qregion.htmlQt::Region].Thiswillsendasinglepainteventforjusttheoneortworectanglesthatneedupdating.<syntaxhighlightlang="ruby">defpaintEvent(event)painter=Qt::Painter.new(self)paintCannon(painter)if@autoShootTimer.isActive()paintShot(painter)endpainter.end()end</code>The paint event function has been simplified since the previous chapter. Most of the logic has been moved to the new '''<tt>paintShot()</tt>''' and '''<tt>paintCannon()</tt>''' functions.<syntaxhighlight lang="ruby">def paintShot(painter) painter.setPen(Qt::NoPen) painter.setBrush(Qt::Brush.new(Qt::black)) painter.drawRect(shotRect())end</code>Thisprivatefunctionpaintstheshotbydrawingablackfilledrectangle.Weleaveouttheimplementationof'''<tt>paintCannon()</tt>''';itisthesameasthe[http://doc.qt.nokia.com/latest/qwidget.html#paintEvent Qt::Widget::paintEvent()] reimplementation from the previous chapter.<syntaxhighlightlang="ruby">defshotRect()gravity=4.0time=@timerCount/20.0velocity=@shootForceradians=@shootAngle*3.14159265/180.0velx=velocity*cos(radians)vely=velocity*sin(radians)x0=(@barrelRect.right()+5.0)*cos(radians)y0=(@barrelRect.right()+5.0)*sin(radians)x=x0+velx*timey=y0+vely*time-0.5*gravity*time*timeresult=Qt::Rect.new(0,0,6,6)result.moveCenter(Qt::Point.new(x.round,height()-1-y.round))returnresultend</code>This private function 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 '''<tt>timerCount</tt>''', which increases as time passes.The formula used is the standard Newtonian formula for frictionless movement in a gravity field. For simplicity, we'vechosentodisregardanyEinsteinianeffects.Wecalculatethecenterpointinacoordinatesystemwhereycoordinatesincreaseupward.Afterwehavecalculatedthecenterpoint,weconstructa[http://doc.qt.nokia.com/latest/qrect.htmlQt::Rect]withsize6x6andmoveitscenterpointtothepointcalculatedabove.Inthesameoperationweconvertthepointintothewidget's coordinate system (see [http://doc.qt.nokia.com/latest/coordsys.html The Coordinate System]).'''[http://www.darshancomputing.com/qt4-qtruby-tutorial/tutorial/t11/t11.rbt11.rb]'''The only addition is the <strong>Shoot</strong> button.<syntaxhighlight lang="ruby">shoot = Qt::PushButton.new(tr('&Shoot'))shoot.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold))</code>In the constructor we create and set up the <strong>Shoot</strong> button exactly like we did with the <strong>Quit</strong> button.<syntaxhighlight lang="ruby">connect(shoot, SIGNAL('clicked()'), cannonField, SLOT('shoot()'))</code>Connects the '''<tt>clicked()</tt>''' signal of the <strong>Shoot</strong>buttontothe'''<tt>shoot()</tt>'''slotofthe'''<tt>CannonField</tt>'''.===RunningtheApplication===Thecannoncanshoot,butthere'snothingtoshootat.===Exercises===Maketheshotafilledcircle.[Hint:[http://doc.qt.nokia.com/latest/qpainter.html#drawEllipse Qt::Painter::drawEllipse()] may help.]Changethecolorofthecannonwhenashotisintheair.[[Category:Ruby]]