gpt4 book ai didi

python - Pygame 移动一个物体

转载 作者:行者123 更新时间:2023-11-28 22:03:45 24 4
gpt4 key购买 nike

所以我想简单地在 pygame 中移动一个对象。我一直在查找教程,但我所能找到的只是如何让它看起来像在下雪,哈哈。我一直在尝试实现该方法来移动对象,但我没有运气。我想要做的就是在屏幕上移动一个对象,当它到达屏幕末端时它会重置并再次移动。所以我试图在屏幕上水平或垂直移动我放入代码中的对象(两个多边形、线和圆),这并不重要。

import pygame, sys, time, random
from pygame.locals import *

pygame.init()

windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Paint")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

windowSurface.fill(WHITE)

pygame.draw.polygon(windowSurface,BLUE,((146, 0), (250, 100), (230, 265), (44, 250), (0,110)))
pygame.draw.polygon(windowSurface,RED,((70, 0), (150, 200), (0, 50)))
pygame.draw.line(windowSurface,BLACK,(60, 60), (120, 60), 8)
pygame.draw.circle(windowSurface, GREEN , (150,150), 15, 0)


pygame.display.update()

while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()

最佳答案

用你的方法,你做不到。使用 pygame 背后的想法是在每一帧中绘制所有你想绘制的对象。您必须首先在 while True 循环内移动绘图。然后,由于您要绘制每一帧的所有内容,您可以:

  • 创建用于存储对象位置和方向的对象/变量
  • 检查对象是否到达屏幕的一个边界
  • 使用新位置绘制多边形

所以最后,你可能会得到类似的东西(你的任务是变成一个对象)

# ... pygame and app initialization

# get screen size
info = pygame.display.Info()
sw = info.current_w
sh = info.current_h

# initial position
x = y = 0
# initial direction
dx = 5
dy = 2

while True:

# update position with direction
x += dx
y += dy

# check bounds
if x - dx < 0 or x + dx > sw:
dx = -dx
if y - dy < 0 or y + dy > sh:
dy = -dy

# then draw and use x/y in your drawing instructions!
# ... pygame events ...

关于python - Pygame 移动一个物体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8441432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com