python - 是否可以在 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))
解决方案
您必须稍微更改应用程序循环中的位置。
定义开始位置 ( 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]
然后必须从列表中的位置设置start
。end
使用列表索引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()
推荐阅读
- julia - 尺寸误差
- excel - 使用连接合并文本和公式,如果单元格不是空白函数
- go - 在 GO 中的 Gorilla 处理程序中实现 LoggingHandlers 中的自定义日志格式
- ruby-on-rails - 除了基本的 CRUD,用户如何更新或删除许多记录?
- python-3.x - 保留原始日期,Xarray Groupby
- ionic3 - 离子 3 下拉菜单
- talend - 使用 Talend Big Data 的每个版本的总缺陷
- angular - 隐藏以角度显示未定义的空字段数据
- unity3d - 从编辑器设置 UnityEvents 并让它们调用正确的参数
- c++ - 想为特征检测构建一些必要的库。有一些错误