我尝试使用time.sleep(1)并将帧速率更改为.5(clock.tick(.5)).
两者都只是在时间间隔过去之后才能使对象改变位置,但是它们也使得鼠标跟随我的鼠标更新坐标的速率相同.
我一直在研究,并且似乎找不到另一种方法来使精灵移动而不会让我的程序刷新更慢或每次运行时“睡眠”.
解决方法 你可以和pygame.time.set_timer()
一起使用 Event
: pygame.time.set_timer()
repeatedly create an event on the event queueset_timer(eventID,milliseconds) -> None
Set an event type to appear on the event queue every given number of milliseconds
这是一个简单,完整的例子.注意敌人每隔1000ms横向移动一次,每3500ms向下移动一次,你可以每450ms射击一次(所有使用事件).
import pygame# you'll be able to shoot every 450msRELOAD_SPEED = 450# the foes move every 1000ms sIDeways and every 3500ms downMOVE_SIDE = 1000MOVE_DOWN = 3500screen = pygame.display.set_mode((300,200))clock = pygame.time.Clock()pygame.display.set_caption("Micro Invader")# create a bunch of events move_sIDe_event = pygame.USEREVENT + 1move_down_event = pygame.USEREVENT + 2reloaded_event = pygame.USEREVENT + 3move_left,reloaded = True,Trueinvaders,colors,shots = [],[],[]for x in range(15,300,15): for y in range(10,100,15): invaders.append(pygame.Rect(x,y,7,7)) colors.append(((x * 0.7) % 256,(y * 2.4) % 256))# set timer for the movement eventspygame.time.set_timer(move_sIDe_event,MOVE_SIDE)pygame.time.set_timer(move_down_event,MOVE_DOWN)player = pygame.Rect(150,180,10,7)while True: clock.tick(40) if pygame.event.get(pygame.QUIT): break for e in pygame.event.get(): if e.type == move_sIDe_event: for invader in invaders: invader.move_ip((-10 if move_left else 10,0)) move_left = not move_left elif e.type == move_down_event: for invader in invaders: invader.move_ip(0,10) elif e.type == reloaded_event: # when the reload timer runs out,reset it reloaded = True pygame.time.set_timer(reloaded_event,0) for shot in shots[:]: shot.move_ip((0,-4)) if not screen.get_rect().contains(shot): shots.remove(shot) else: hit = False for invader in invaders[:]: if invader.collIDerect(shot): hit = True i = invaders.index(invader) del colors[i] del invaders[i] if hit: shots.remove(shot) pressed = pygame.key.get_pressed() if pressed[pygame.K_left]: player.move_ip((-4,0)) if pressed[pygame.K_RIGHT]: player.move_ip((4,0)) if pressed[pygame.K_SPACE]: if reloaded: shots.append(player.copy()) reloaded = False # when shooting,create a timeout of RELOAD_SPEED pygame.time.set_timer(reloaded_event,RELOAD_SPEED) player.clamp_ip(screen.get_rect()) screen.fill((0,0)) for invader,(a,b) in zip(invaders,colors): pygame.draw.rect(screen,(150,a,b),invader) for shot in shots: pygame.draw.rect(screen,(255,0),shot) pygame.draw.rect(screen,(180,180),player) pygame.display.flip()总结
以上是内存溢出为你收集整理的python – 在Pygame中每隔几秒移动一个对象全部内容,希望文章能够帮你解决python – 在Pygame中每隔几秒移动一个对象所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)