import pygame
import sys
import math
def main():
pygame.init()
screen = pygame.display.set_mode((800, 700), 0, 32)
missile_image = pygame.image.load('D:/daku/导弹追踪/red_pointer.png').convert_alpha()
# 调整导弹图像的大小
missile_size = (50, 50) # 初始大小
missile_image = pygame.transform.scale(missile_image, missile_size)
x1, y1 = 100, 600 # 导弹的初始位置
velocity = 400 # 导弹速度
clock = pygame.time.Clock()
angle = 0
trail = [] # 导弹轨迹列表
trail_max_length = 100 # 轨迹的最大长度
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 获取两帧之间的时间差
dt = clock.tick(300) / 1000.0
x, y = pygame.mouse.get_pos()
distance = math.sqrt((x1 - x) ** 2 + (y1 - y) ** 2)
# 计算新的位置
section = velocity * dt
sina = (y1 - y) / distance
cosa = (x - x1) / distance
angle = math.atan2(y - y1, x - x1)
# 更新导弹的位置
x1 += section * cosa
y1 -= section * sina
# 保存导弹位置到轨迹列表
trail.append((x1, y1))
# 如果轨迹列表超过了最大长度,则删除最老的位置
if len(trail) > trail_max_length:
trail.pop(0)
# 旋转导弹图像
rotated_missile = pygame.transform.rotate(missile_image, math.degrees(angle))
# 调整导弹图像大小,使其随着距离目标越近而变小
size_reduction_factor = max(1, min(2, distance / 200)) # 限制大小变化在 1 到 2 之间
adjusted_size = (int(missile_size[0] / size_reduction_factor), int(missile_size[1] / size_reduction_factor))
adjusted_rotated_missile = pygame.transform.scale(rotated_missile, adjusted_size)
# 获取旋转后导弹的新矩形
rotated_rect = adjusted_rotated_missile.get_rect(center=missile_image.get_rect(center=(x1, y1)).center)
# 清除屏幕并绘制导弹
screen.fill((0, 0, 0)) # 清除屏幕
screen.blit(adjusted_rotated_missile, rotated_rect.topleft)
# 绘制导弹轨迹
for pos in trail:
pygame.draw.circle(screen, (173, 216, 230), pos, 2)
pygame.display.update()
if __name__ == "__main__":
main()
基于Pygame模拟导弹追踪
最新推荐文章于 2024-08-13 18:29:56 发布