python - 获取 PygAnimation 对象的 x 和 y 位置以进行碰撞检测
问题描述
我即将使用动画 PygAnimation 对象(青蛙)创建一个类似十字路口的游戏,并且需要找到对象的 x 和 y 位置以检查与敌人(丢失条件)和宝藏(获胜条件)的碰撞. 动画本身正在运行:
if moveUp or moveDown or moveLeft or moveRight:
if direction == UP:
animObjs['back_walk'].blit(windowSurface, (x, y))
elif direction == DOWN:
animObjs['front_walk'].blit(windowSurface, (x, y))
elif direction == LEFT:
animObjs['left_walk'].blit(windowSurface, (x, y))
elif direction == RIGHT:
animObjs['right_walk'].blit(windowSurface, (x, y))
AnimObjs 已加载到字典中,但我无法访问每个字符的 x 和 y 值。我觉得有一个简单的解决方案,但我对编程很陌生,到目前为止还没有找到它。敌人是 NonPlayerCharacter(GameObject) 类的一部分,x 和 y 值仅通过 image_path、self.x_pos 和 self.y_pos 访问。但是对于动画,我似乎无法以相同的方式访问它,因为动画似乎被不同地对待。
以下代码在运行游戏循环中,仅用于上传站立和移动条件的 gif:
front_standing = pygame.image.load('frog_front.gif')
back_standing = pygame.image.load('frog_back.gif')
left_standing = pygame.image.load('frog_left.gif')
right_standing = pygame.transform.flip(left_standing, True, False)
playerWidth, playerHeight = front_standing.get_size()
# creating the PygAnimation objects for walking in all directions
animTypes = 'back_walk front_walk left_walk'.split()
animObjs = {}
animObjs['back_walk'] = pyganim.PygAnimation('frog_back_walk.gif')
animObjs['front_walk'] = pyganim.PygAnimation('frog_front_walk.gif')
animObjs['left_walk'] = pyganim.PygAnimation('frog_left_walk.gif')
# create the right-facing sprites by copying and flipping the left-facing sprites
animObjs['right_walk'] = animObjs['left_walk'].getCopy()
animObjs['right_walk'].flip(True, False)
animObjs['right_walk'].makeTransformsPermanent()
moveConductor = pyganim.PygConductor(animObjs)
direction = DOWN # player starts with facing down (front)
敌人等级如下:
类 NonPlayerCharacter(GameObject): SPEED = 10
def __init__(self,image_path, x, y, width, height):
super().__init__(image_path, x, y, width, height)
def move(self, max_width):
# automating of movement
if self.x_pos <= 20:
self.SPEED = abs(self.SPEED)
elif self.x_pos >= max_width - 40:
self.SPEED = -abs(self.SPEED)
self.x_pos += self.SPEED
敌人只是从左到右在屏幕上移动,这是访问每个敌人的方式:
enemy_0 = NonPlayerCharacter("enemy.png", 20, 600, 50, 50)
我将衷心感谢您的帮助。我认为这只是一件小事。:-)
解决方案
查看pygAnimation source,您可以使用.getRect()
,然后将其定位到上x,y
一个 blit 的最后使用的位置。看起来 pygAnimations 不会在内部存储位置。
但是,getRect()
返回所有动画帧的最大宽度和高度,这可能不是您想要的碰撞。特别是在动画序列期间精灵大小发生显着变化时。
所以,也许这样的事情会做,使用getCurrentFrame()
:
def getCurrentRect( position, animation ):
""" Get the positioned rect of the current pygAnimation frame """
current_image = animation.getCurrentFrame()
rect = current_image.get_rect()
rect.topleft = position # do you draw at top-left?
return rect
推荐阅读
- travis-ci - 如何共享 Travis-CI 中使用的凭据
- cakephp-3.8 - 在查询生成器中创建文本,选择
- python - 如何将预训练的 Tensorflow 模型从 Google Cloud Storage 加载到 Datalab
- c# - BarBackgroundColor 仅更改导航栏,而不更改标题栏
- java - Jodatime 时差给出否定结果
- scala - 具有多个参数的类型类。如何召唤一个只有一个参数的实例?
- python - 使用 PIL 删除 exif 时文件大小增加而不是减少?
- javascript - 在 React 中向子组件传播事件
- r - R客户状态连接字符串
- r - 向 Shiny DT 添加按钮以拉起模态