Skip to main content
 首页 » 编程设计

python之计算自上次刻度以来的 x 和 y 坐标变化

2025年05月04日8tuyile006

我正在使用 PyGame 创建自动移动的单位。 可以为这些单元指定一个包含两个元素 (x, y) 的元组类型的目的地,并且这些单元具有静态速度。

我正在调用 units.update(dt),其中 dt 是自上次更新以来的时间(以毫秒为单位)。我需要计算自上次更新以来单位移动了多少。这是我的 Unit 类:

class Unit(pygame.sprite.Sprite): 
    def __init__(self, image, speed): 
       self.image = pygame.image.load(image) 
       self.rect = self.image.get_rect()  # This rect contains x and y for the Unit 
       self.speed = speed 
       self.destination = None 
 
    def update(self, dt): 
        if self.destination is not None and self.speed > 0: 
            dist = self.speed * dt 

这样我可以获得斜边 (dist),但是我需要 self.rect.x 和 self.rect.y< 的单独方向。如何从 dist 获取 dx 和 dy?

此外,这是我的 main.py:

import unit 
import pygame 
 
pygame.init() 
display = pygame.display.set_mode((960, 720)) 
units = pygame.sprite.Group() 
my_unit = unit.Unit('my_image.png', 3) 
units.add(my_unit) 
my_unit.destination = (150, 150) 
clock = pygame.time.Clock() 
 
running = True 
while running: 
    dt = clock.tick(30) 
    units.update(dt) 
    display.fill((0, 0, 0)) 
    units.draw(display) 
    pygame.display.update() 
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            running = False 

请您参考如下方法:

您可以在 Unit 类中添加一个变量,将当前位置存储为元组,就像方向一样。我猜它会在(0,0)处初始化?

每次更新,计算从当前位置到目的地的角度。一些基本的三角函数会给你 dx/dy,就像你说的你已经有了斜边。
在这部分我帮不了你更多,因为这取决于你的单位如何移动(对角线),速度代表什么,...... 不要忘记之后更新当前位置。