python - Pygame 玩家在击中另一个 obj 时跳回落下
问题描述
我正在制作一个简单的 Pygame 游戏。这是我的代码:
import pygame
def gravity(player_bottom):
if player_bottom >= 500:
Player.jumpable = True
return 500
else:
player_bottom += gravity_strength
return player_bottom
def create_ground(width, height, x ,y):
rect = pygame.Rect((x, y), (width, height))
grounds.append(rect)
def draw_grounds(grounds):
for ground in grounds:
pygame.draw.rect(screen, (0,0,0), ground)
def collision_ground(grounds):
collision_tol = 10
for ground in grounds:
if Player.hero_rect.colliderect(ground):
if abs(Player.hero_rect.left - ground.right) < collision_tol:
Player.hero_rect.left = ground.right
if abs(Player.hero_rect.right - ground.left) < collision_tol:
Player.hero_rect.right = ground.left
if abs(Player.hero_rect.top - ground.bottom) < collision_tol:
Player.hero_rect.top = ground.bottom
if abs(Player.hero_rect.bottom - ground.top) < collision_tol:
Player.hero_rect.bottom = ground.top
class player:
def __init__(self):
self.jumpable = False
self.second_jump = False
self.vel = 3
self.jump_power = 50
self.x = 50
self.y = 10
self.hero_rect = hero.get_rect(center = (self.x, self.y))
def draw(self):
screen.blit(hero, self.hero_rect)
def jump(self):
if self.jumpable:
self.jumpable = False
self.second_jump = True
self.hero_rect.y -= self.jump_power
elif self.second_jump:
self.second_jump = False
self.hero_rect.y -= self.jump_power
def back(self):
self.hero_rect.x -= self.vel
def forward(self):
self.hero_rect.x += self.vel
pygame.init()
screen = pygame.display.set_mode((700, 500))
screen.fill((255,255,255))
# images
hero = pygame.image.load("assets/hero/blue.png").convert_alpha()
# game val
gravity_strength = 1
grounds = []
Player = player()
create_ground(100, 10, 350, 400)
GRAVITY = pygame.USEREVENT
TOUCH_SUR = pygame.USEREVENT + 1
pygame.time.set_timer(GRAVITY, 10)
pygame.time.set_timer(TOUCH_SUR, 1)
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
Player.jump()
if event.type == GRAVITY:
Player.hero_rect.bottom = gravity(int(Player.hero_rect.bottom))
if event.type == TOUCH_SUR:
collision_ground(grounds)
# front back movement
keys=pygame.key.get_pressed()
if keys[pygame.K_a]:
Player.back()
if keys[pygame.K_d]:
Player.forward()
screen.fill((255,255,255))
Player.draw()
draw_grounds(grounds)
pygame.display.update()
clock.tick(60)
一切都很好,除了玩家的跳跃,它保持在 Rect 表面上的传送。LZ,请告诉我如何解决这个问题,非常感谢。
解决方案
推荐阅读
- symfony4 - 如何在构造symfony中使用循环和不同参数调用两个类
- php - Web 项目:多实例与单实例
- informix - 将sql的结果存储在informix中处理
- python - 以 80:20 的百分比将用户随机分成两组
- excel - 从sql获取数据到excel时失败
- swift - UILabel - 相等截断
- xml - XSLT 删除无序列表中包含的特定 unicode
- amazon-web-services - aws CodeDeploy 与 aws Lambda
- python-3.x - 第一个视频文件正确保存后如何获取视频文件
- python - 如何将字段格式从 epoh 更改为 date