首页 > 解决方案 > 是否可以在 Pygame 中实现对象逐渐移动到给定坐标?

问题描述

这是我尝试过的示例代码:

x[0] = 10
y[0]=10
x[1] = 40
y[1]=40
width=10
height=10
pygame.draw.rect(win,(0,0,255),(x[1],y[1],width,height))
pygame.draw.rect(win,(0,0,255),(x[0],y[0],width,height))

标签: pythonpygame

解决方案


您必须稍微更改应用程序循环中的位置。

定义开始位置 ( start)、结束位置 ( end) 和速度 ( speed):

start = 10, 10
end = 40, 40
speed = 1

初始化当前位置。在应用程序循环中计算从当前位置到结束位置 ( dx, dy) 的向量,并通过朝向目标方向的速度改变当前位置:

pos = start[:]
while run:
    # [...]

    dx = end[0] - pos[0]
    dy = end[1] - pos[1]
    dist = math.sqrt(dx*dx + dy*dy)
    if dist > speed:
        pos = pos[0] + dx*speed/dist, pos[1] + dy*speed/dist

注意,math.hypot计算欧几里得距离并且(dx/dist, dy/dist)单位向量(单位向量的长度为 1)。

pos在每一帧的当前位置 ( ) 绘制对象:

pygame.draw.rect(win,(0,0,255),(round(pos[0]), round(pos[1]), width, height))

如果您有职位列表:

x = [60, 140, 140, 60]
y = [60, 140, 60,  140]

然后必须从列表中的位置设置startend使用列表索引current_i来跟踪当前开始位置。如果对象已到达当前目标位置 ( end),则增加索引。
请参阅示例:

import pygame
import math

pygame.init()
win = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()

x = [60, 140, 140, 60]
y = [60, 140, 60,  140]

width, height = 10, 10
speed = 1
current_i = 0
pos = x[current_i], y[current_i]

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    start = x[current_i], y[current_i]
    end = x[current_i % len(x)], y[current_i % len(y)], 
    dx = end[0] - pos[0]
    dy = end[1] - pos[1]
    dist = math.hypot(dx, dy)
    if dist > speed:
        pos = pos[0] + dx*speed/dist, pos[1] + dy*speed/dist
    else:
        pos = end[:]
        current_i = current_i + 1 if current_i < len(x)-1 else 0

    win.fill(0)
    pygame.draw.rect(win,(0,0,255),(round(pos[0]), round(pos[1]), width, height))
    pygame.display.flip()

推荐阅读