这是我创建的代码,它将是一个简单的2D游戏。我在制作另一个游戏时尝试使用类,以使其功能更强大、更有条理。但问题是,当我运行代码并尝试在main()函数中移动玩家时,当我按下按钮时,玩家的位置并没有改变。
import pygame as pg
\#------------------------------------------------------------------------------------
# Colors
RED = (255,0,0)
GREEN = (0, 255, 0)
BLUE = (0,0,255)
WHITE = (255,255,255)
BLACK = (0,0,0)
\#------------------------------------------------------------------------------------
# Constants
FPS = 60
WIDTH, HEIGHT = 1400, 900
P_VEL = 10
\#------------------------------------------------------------------------------------
# Variables
\#------------------------------------------------------------------------------------
# Objects
\#------------------------------------------------------------------------------------
# Fonts
\#------------------------------------------------------------------------------------
# Sprites
\#------------------------------------------------------------------------------------
# Sounds
\#------------------------------------------------------------------------------------
WINDOW = pg.display.set_mode((WIDTH,HEIGHT))
pg.display.set_caption("Game Project")
\#------------------------------------------------------------------------------------
class Hero:
def __init__(self, x_cord, y_cord, width, height):
self.xc = x_cord
self.yc = y_cord
self.width = width
self.height = height
self.hero = pg.Rect(self.xc,self.yc,self.width,self.height)
def player_movement(self, keys_pressed):
if keys_pressed[pg.K_d]:
self.xc += P_VEL
if keys_pressed[pg.K_a]:
self.xc -= P_VEL
if keys_pressed[pg.K_w]:
self.yc -= P_VEL
if keys_pressed[pg.K_s]:
self.yc += P_VEL
def draw(self):
pg.draw.rect(WINDOW, GREEN, self.hero)
player = Hero(500,400,40,60)
def gravis():
WINDOW.fill(BLACK)
player.draw()
pg.display.update()
def main():
clock = pg.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pg.event.get():
if event.type == pg.QUIT:
run = False
keys_pressed = pg.key.get_pressed()
player.player_movement(keys_pressed)
gravis()
main()
我试着在youtube上搜索答案,并查看代码,但我什么也没找到。
2条答案
按热度按时间hc8w905p1#
试用你的程序,按下按钮是更新你的对象的x和y坐标;然而,hero属性并没有改变,因为它是通过pg.Rect()函数定义和构建的。当我在draw()函数中添加一行代码时,有一个响应,矩形移动了。
给予一下,看看它是否符合你项目的精神。
23c0lvtd2#
如果您更改
self.xc
或self.yc
,则存储在self.hero
中的位置不会更改。但是,self.hero
用于绘制矩形。因此,您必须在更改self.xc
或self.yc
后更新self.hero
: