📅  最后修改于: 2023-12-03 14:46:27.286000             🧑  作者: Mango
在使用 PyGame 开发 2D 游戏时,有时需要让游戏角色跳跃或者躲避障碍物。本文将介绍如何在 PyGame 中使对象跳跃。
import pygame
pygame.init()
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Jumping Object')
class Character(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((50, 50))
self.image.fill((255, 255, 255))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.gravity = 1
self.velocity = 0
def jump(character):
character.velocity -= 20
character.rect.y += character.velocity
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
jump(character)
character.velocity += character.gravity
character.rect.y += character.velocity
window.fill((0, 0, 0))
window.blit(character.image, character.rect)
pygame.display.update()
import pygame
import sys
pygame.init()
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Jumping Object')
class Character(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface((50, 50))
self.image.fill((255, 255, 255))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.gravity = 1
self.velocity = 0
def jump(character):
character.velocity -= 20
character.rect.y += character.velocity
character = Character(100, 400)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
jump(character)
character.velocity += character.gravity
character.rect.y += character.velocity
window.fill((0, 0, 0))
window.blit(character.image, character.rect)
pygame.display.update()
通过本文的介绍,你学会了如何在 PyGame 中使对象跳跃。使用这个技巧,你可以开发更加有趣和具有挑战性的 2D 游戏。