Implementing Automatic Missile Tracking in Python with Pygame
This article explains the mathematics and step‑by‑step Python pygame implementation of an automatic missile‑tracking algorithm for shooting games, covering time‑slice calculations, trigonometric direction computation, and image rotation handling to keep the missile tip aligned with the target.
Automatic missile tracking is a common technique in shooting games, which can be derived from solving differential equations and using simple trigonometry.
The algorithm divides time into small intervals, constructs a triangle each interval to compute the direction (angle a) and distance (vt) the missile should travel, updates the missile position, and repeats.
Key formulas: distance between missile and target, sin(a) = (y1‑y)/distance, cos(a) = (x‑x1)/distance, and the new position is x1+vt*cos(a), y1‑vt*sin(a).
Implementation in Python with pygame:
<code>import pygame,sys
from math import *
pygame.init()
screen=pygame.display.set_mode((800,700),0,32)
missile=pygame.image.load('element/red_pointer.png').convert_alpha()
x1,y1=100,600 # missile start
velocity=800
time=1/1000
clock=pygame.time.Clock()
old_angle=0
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
clock.tick(300)
x,y=pygame.mouse.get_pos()
distance=sqrt(pow(x1-x,2)+pow(y1-y,2))
section=velocity*time
sina=(y1-y)/distance
cosa=(x-x1)/distance
angle=atan2(y-y1,x-x1)
x1,y1=(x1+section*cosa,y1-section*sina)
d_angle = degrees(angle)-old_angle
old_angle = degrees(angle)
missiled = pygame.transform.rotate(missile, -degrees(angle))
screen.blit(missiled, (x1-missile.get_width(), y1-missile.get_height()/2))
pygame.display.update()</code>To keep the missile tip aligned after rotation, the code computes the rotated image’s head position and adjusts the blit coordinates accordingly, handling four angle quadrants.
Full source code with quadrant handling is provided, enabling a smooth missile‑tracking demo.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.