如何解决如何使用精灵动画检查瓷砖物理和碰撞?
我对 pygame 很陌生,这是我的第一个基本游戏代码。我正在制作一个平台游戏,我已经渲染了所有内容,瓷砖,背景,精灵和精灵行走动画。现在我需要物理学,我很难理解如何去做。我知道你可以使用 rect 但据我所知,大多数 youtubers 都告诉我如何使用 rect 和一个精灵图像,而不是多个。也许我可以尝试不同的路线,你们建议我做什么?
import pygame
pygame.init()
class Player(object):
def __init__(self,x,y):
self.veLocity=4
self.x = x
self.y = y
self.jumping=False
self.right=False
self.left=False
self.jumptotal=10
self.walkcount=0
self.player_hitBox=(self.x+1,self.y,60,60)
def hitBox(self,window):
self.player_hitBox = (self.x,47,83)
pygame.draw.rect(window,(255,0),self.player_hitBox,2)
running=True
player=Player(20,600)
def draw_game():
global player
window.blit(background,(0,0))
if player.walkcount + 1 > 45:
player.walkcount = 0
if player.right:
window.blit(walk_right[player.walkcount // 3],(player.x,player.y))
player.walkcount += 1
elif player.left:
window.blit(walk_left[player.walkcount // 3],(player.x-50,player.y))
player.walkcount += 1
else:
window.blit(idle,player.y))
player.hitBox(window)
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
key_press=pygame.key.get_pressed()
if key_press[pygame.K_LEFT] and player.x>player.veLocity:
player.x-=player.veLocity
player.right=False
player.left=True
elif key_press[pygame.K_RIGHT] and player.x<2300-player.x-player.veLocity:
player.x+=player.veLocity
player.right = True
player.left = False
else:
player.right=False
player.left=False
player.walkcount=0
if key_press[pygame.K_UP]:
player.jumping=True
if player.jumping:
if player.jumptotal>=-10:
jumpside=1
if player.jumptotal<0:
jumpside=-1
player.y-=(player.jumptotal**2)*0.3*jumpside
player.jumptotal-=1
else:
player.jumping=False
player.jumptotal=10
pygame.display.update()
pygame.quit()
解决方法
我认为您正在寻找:
pygame.sprite.collide_rect()
pygame.sprite.collide_circle()
文档: https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_rect
这将返回一个布尔值并检查两个命中框是否重叠
pygame.sprite.collide_rect(sprite1,sprite2)
编辑: 使用 Pygame 组 也被认为是一种很好的做法 https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group
pygame.sprite.Group
正如@pavel 指出的,这允许您使用:
pygame.sprite.spritecollideany()
检查精灵是否击中了组中的任何精灵
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。