自动跟踪目标的旋转炮塔
同样是写飞机游戏时用的。程序代码:
Option Explicit Private Type point X As Integer Y As Integer End Type Dim target As point Dim cur_angle As Single Dim r As Integer Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) Select Case KeyCode Case Is = 65 target.X = target.X - 5 If target.X < 0 Then target.X = 0 Case Is = 68 target.X = target.X + 5 If target.X > 400 Then target.X = 400 Case Is = 87 target.Y = target.Y - 5 If target.Y < 0 Then target.Y = 0 Case Is = 83 target.Y = target.Y + 5 If target.Y > 400 Then target.Y = 400 End Select End Sub Private Sub Form_Load() target.X = 300 target.Y = 300 cur_angle = 1.5 * 3.14 r = 25 Timer1.Interval = 40 End Sub Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) 'target.X = X 'target.Y = Y End Sub Private Sub Timer1_Timer() Form1.Cls Form1.Circle (target.X, target.Y), 5 rotate Form1.Caption = cur_angle End Sub Function direction(x0, y0, x1, y1 As Integer) As Boolean Dim temp As Single If x0 = x1 And y1 >= y0 Then temp = 3.14 / 2: GoTo loop1 If x0 = x1 And y1 < y0 Then temp = 1.5 * 3.14: GoTo loop1 temp = Atn((y1 - y0) / (x1 - x0)) If x1 < x0 Then temp = temp + 3.14 If x1 > x0 And y1 < y0 Then temp = temp + 6.28 direction = True 'count clockwise loop1: Select Case cur_angle > 3.14 Case Is = True If temp > cur_angle - 3.14 And temp < cur_angle Then direction = False 'clockwise Case Is = False If temp > cur_angle + 3.14 Or temp < cur_angle Then direction = False End Select End Function Sub rotate() Dim temp As Single Dim temp1 As Boolean temp1 = direction(200, 200, target.X, target.Y) Select Case temp1 Case Is = False temp = -2 * 3.14 / 180 Case Is = True temp = 2 * 3.14 / 180 End Select cur_angle = cur_angle + temp If cur_angle > 6.28 Then cur_angle = cur_angle - 6.28 If cur_angle < 0 Then cur_angle = cur_angle + 6.28 Line1.X2 = 200 + r * Cos(cur_angle) Line1.Y2 = 200 + r * Sin(cur_angle) End Sub窗体中添加1个Timer控件,在窗体中间添加1个圆形的Shape1和1个Line1控件,如下图
[ 本帖最后由 lianyicq 于 2015-7-15 14:48 编辑 ]