davidmou 发表于 2023-9-2 08:13:23

pygame的速度问题

import sys
import pygame
import os
from pygame.locals import *
os.chdir("C:\\Users\\david\\Desktop")
pygame.init()
size = width,height = 600,400
bg =
x_speed =2
y_speed = 2
speed =
fullscreen = False
screen = pygame.display.set_mode(size)
photo = pygame.image.load("uu.gif")
position = photo.get_rect()
while 1:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
            sys.exit()
      #按左右建控制速度:
      if event.type == KEYDOWN:

            if event.key == K_RIGHT:
               
                x_speed += 5
            if event.key == K_LEFT:
                x_speed -= 1
            #按键h全屏
            if event.key == K_h:
                print("hdjhj")
                fullscreen = not fullscreen
                if fullscreen:
                  screen = pygame.display.set_mode(size,FULLSCREEN | HWSURFACE)
                else:
                  pass


    position = position.move(speed)
    if position.left <0 or position.right > width:
      photo = pygame.transform.flip(photo,True,False)
      speed = -speed
    if position.top < 0 or position.bottom > height:
      speed = -speed
    screen.fill(bg)
    screen.blit(photo,position)
    pygame.display.flip()
    pygame.time.delay(10)
    问一下为什么当按下右键左键时,图片速度没变化

isdkz 发表于 2023-9-2 08:13:41

问题出在事件处理部分的代码上。在按下左右键时,虽然改变了变量 x_speed 的值,但是并没有更新 speed 变量的值。因此,图片的速度没有发生变化。

为了解决这个问题,需要在按下左右键时,更新 speed 变量的值。具体地,当按下右键时,将 x_speed 增加5;当按下左键时,将 x_speed 减少1。然后,将 speed 变量的值设置为 。

以下是修改后的代码:

import sys
import pygame
import os
from pygame.locals import *

os.chdir("C:\\Users\\david\\Desktop")
pygame.init()
size = width, height = 600, 400
bg =
x_speed = 2
y_speed = 2
speed =
fullscreen = False
screen = pygame.display.set_mode(size)
photo = pygame.image.load("uu.gif")
position = photo.get_rect()

while True:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
            sys.exit()
      if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                x_speed += 5
            if event.key == K_LEFT:
                x_speed -= 1
            if event.key == K_h:
                print("hdjhj")
                fullscreen = not fullscreen
                if fullscreen:
                  screen = pygame.display.set_mode(size, FULLSCREEN | HWSURFACE)
                else:
                  pass

    speed = # 更新速度
    position = position.move(speed)
    if position.left < 0 or position.right > width:
      photo = pygame.transform.flip(photo, True, False)
      speed = -speed
    if position.top < 0 or position.bottom > height:
      speed = -speed
    screen.fill(bg)
    screen.blit(photo, position)
    pygame.display.flip()
    pygame.time.delay(10)


通过以上修改,当按下左右键时,图片的速度会发生相应的变化。

davidmou 发表于 2023-9-2 08:20:50

为什么x_speed和y_speed改变后还要更新speed
页: [1]
查看完整版本: pygame的速度问题