[英]How do I change character's image based on user's last input key?
我可以讓我的角色左右奔跑。 我試圖根據用戶的輸入使我的角色朝某個方向看。 如果用戶的最后一個命令是“a”或“K_LEFT”,那么我想讓他看向左方向。 否則讓他朝正確的方向看。 我不知道如何實現這一點。 我在 pygame 文檔中查看了 KEYUP,但我無法理解它。 有人可以在這里幫助我嗎? 這是代碼 -
def animate_char(self):
keys = pygame.key.get_pressed()
is_resting_forward = True
if self.rect.bottom != 470:
self.image = self.player_jump
elif keys[pygame.K_d] or keys[pygame.K_RIGHT]:
self.hero_index += 0.15
if self.hero_index >= len(self.images_runf_list):
self.hero_index = 0
self.image = self.images_runf_list[int(self.hero_index)]
elif keys[pygame.K_a] or keys[pygame.K_LEFT]:
self.hero_index += 0.15
if self.hero_index >= len(self.images_runb_list):
self.hero_index = 0
self.image = self.images_runb_list[int(self.hero_index)]
is_resting_forward = False
else:
if is_resting_forward:
self.image = self.image_restf
else:
self.image = self.image_restb
我沒有從這段代碼中得到我想要的東西。 每次我抬起任何鍵時,該字符都會設置self.image_restf
的值。
is_resting_forward
必須是類的屬性。 根據按下的鍵設置屬性:
def __init__(self, ......):
# [...]
self.is_resting_forward = True
def animate_char(self):
keys = pygame.key.get_pressed()
if self.rect.bottom != 470:
self.image = self.player_jump
elif keys[pygame.K_d] or keys[pygame.K_RIGHT]:
self.hero_index += 0.15
if self.hero_index >= len(self.images_runf_list):
self.hero_index = 0
self.image = self.images_runf_list[int(self.hero_index)]
self.is_resting_forward = True
elif keys[pygame.K_a] or keys[pygame.K_LEFT]:
self.hero_index += 0.15
if self.hero_index >= len(self.images_runb_list):
self.hero_index = 0
self.image = self.images_runb_list[int(self.hero_index)]
slef.is_resting_forward = False
else:
if self.is_resting_forward:
self.image = self.image_restf
else:
self.image = self.image_restb
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.