2013년 9월 16일 월요일

About homing missile algorithm (Corona SDK)

  In my recently released game (Lunar Blast) that is developed using Corona SDK, a homing missile (that tracks moving enemy) have been adopted as one of the sub-weapons. In this blog post, I will explain the detailed tracking algorithm developed.


 Let's consider the following figure.


  The current x- and y-coordinates and rotational angle of the missile are marked as x_m[k], y_m[k], and theta_m[k], respectively. The index [k] designates current frame. Enemy target is randomly determined and the current x- and y-coordinates of the target are described as x_t[k] and y_t[k].

  In every enterFrame events, the following calculations are performed. Direction vector must be firstly obtained by subtracting missile x and y values from those of the target.

          dxt = x_t[k] - x_m[k]
          dyt = y_t[k] - y_m[k]

The rotating angle that can be obtained by this direction vector is a desired (perfect) one for the missile. However, setting this rotating angle directly to the missile make the curving movement very steep and awkward. For the smooth turning movement, the following algorithm has been developed.

The unit vector (length 1) of this vector is obtained by dividing these values by its length.

          dist = math.sqrt ( dxt*dxt + dyt*dyt )
          dxt = dxt/dist
          dyt = dyt/dist

The increment of x and y values of the missile can be calculated by the following equations. These equations play a key role to make the missile move smoothly.

          dx[k] = ga * dx[k-1] + (1-ga) * dxt
          dy[k] = ga * dy[k-1] + (1-ga) * dyt

In this equations, variable ga has a value of real number between 0 to 1. The closer to 0 ga is (for example, 0,2, 0.1, 0,05, etc), the faster the turning speed is. If the ga is close to 1, (for example 0,9, 0.95, 0,99 etc) the curving speed becomes very slow. The dx[k-1] ( or dy[k-1] ) means the dx (or dy) value of the previous frame. Thus, these values are to be stored for the next frame.

  Finally, the updated coordinates and rotational angle of the missile is calculated as follows

          x_m[k+1] = x_m[k] + dx[k]*vel
          y_m[k+1] = y_m[k] + dy[k]*vel
          theta_m[k+1] = atan2(dy[k], dx[k])*_r2d + 90

where variable vel is a linear speed of the missile and _r2d is a (constant) variable that converts radian to degree. (_r2d = 180/3.14). The vel value determines moving speed of the missile.

  The actual code sinppet of Update() function of the homing missile is here. Every enterFrame events call this Update() function. Variable bb is the missile sprite object.



You can check the movement of the homing missile with the algorithm in the following video clip.


The similar algorithm is also applied to the movement of side planes, and to the slow rotation of the big final bosses etc.

댓글 없음:

댓글 쓰기