# Archive:Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11 (zh TW)

## Giving It a Shot

### 一行一行的瀏覽

CannonField 現在有射擊能力了。

include Math

@timerCount = 0

@autoShootTimer = Qt::Timer.new(self)
connect(@autoShootTimer, SIGNAL('timeout()'),
self, SLOT('moveShot()'))

@shootAngle = 0
@shootForce = 0

timerCount 會不斷追踪發射後經過的時間。shootAngle 是加農砲發射時的角度，而 shootForce 是加農砲發射時的力量。

def shoot()
if @autoShootTimer.isActive()
return
end;

@timerCount = 0
@shootAngle = @currentAngle
@shootForce = @currentForce
@autoShootTimer.start(5)
end

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

moveShot() 是一個移動砲彈的槽，當Qt::Timer啟動後，每5毫秒被呼叫一次。

def paintEvent(event)
painter = Qt::Painter.new(self)

paintCannon(painter)
if @autoShootTimer.isActive()
paintShot(painter)
end

painter.end()
end

def paintShot(painter)
painter.setPen(Qt::NoPen)
painter.setBrush(Qt::Brush.new(Qt::black))
painter.drawRect(shotRect())
end

def shotRect()
gravity = 4.0

time = @timerCount / 20.0
velocity = @shootForce
radians = @shootAngle * 3.14159265 / 180.0

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

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

shoot = Qt::PushButton.new(tr('&Shoot'))
shoot.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold))

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