python - Pygame 碰撞处理
问题描述
我用 pygame 制作了一个 2D 平台游戏。我正在努力弄清楚如何确定物体移动的方向。
例如:假设玩家从上面来,因为他的 y 速度大于零,那么问题是他的引力一直在作用于他;这意味着如果他来自左侧,他的 y 速度大于零(因此即使我希望触发左侧 if 语句,也会触发这个 if 语句)。
源代码如下:`
if self.hits:
for platform in self.hits:
if self.player.vel.y > 0:
self.player.rect.y = platform.rect.top
self.player.vel.y = 0
if self.player.vel.y < 0:
self.player.rect.top = platform.rect.bottom
self.player.vel.y = 0
if self.player.vel.x > 0:
self.player.rect.right = platform.rect.left
if self.player.vel.y < 0:
self.player.rect.left = platform.rect.right
这就是为什么我为每个四个方向的识别设置了一些限制:`
if self.hits:
for platform in self.hits:
if self.player.rect.bottom >= (platform.rect.top) and self.player.rect.bottom <= (platform.rect.top + 16)\
and (self.player.rect.centerx + 13) >= platform.rect.left and (self.player.rect.centerx - 13) <= platform.rect.right:
self.player.pos_bottom.y = platform.rect.top
self.player.vel.y = 0
elif self.player.rect.top <= (platform.rect.bottom) and self.player.rect.top >= (platform.rect.bottom - 16)\
and (self.player.rect.centerx + 13) >= platform.rect.left and (self.player.rect.centerx - 13) <= platform.rect.right:
self.player.rect.top = platform.rect.bottom
self.player.vel.y = 0
elif self.player.rect.right >= (platform.rect.left) and self.player.rect.right <= (platform.rect.right + 10) and self.player.vel.x >= 0\
and self.player.rect.centery >= platform.rect.top and self.player.rect.centery <= platform.rect.bottom:
self.player.rect.right = platform.rect.left
self.player.vel.x = 0
elif self.player.rect.left <= (platform.rect.right) and self.player.rect.left >= (platform.rect.right - 10) and self.player.vel.x <= 0\
and self.player.rect.centery >= platform.rect.top and self.player.rect.centery <= platform.rect.bottom:
self.player.rect.left = platform.rect.right
self.player.vel.x = 0`
这段代码限制了玩家方向被识别的区域,但也带来了很多错误,也很丑陋。
解决方案
推荐阅读
- html - 上下颠倒的CSS方向?
- spring - Spring boot 2.2.0 升级后导致按占位符读取值的问题
- kubernetes - 总是出现错误:您必须登录到服务器(未经授权)EKS
- c++ - 使用 Boost SML 组成状态机来管理 ASIO 对象和线程的最佳方法是什么?
- bash - 找到如何排除路径
- autohotkey - 切换键盘布局有效但并非总是如此
- php - 如何使用chart.js在php中的饼图或条形图上显示值
- sql - 在字段中查找指定值,但不显示该字段中最后一条记录为“1100”的任何记录
- apache-spark - 在多个数组类型元素之间过滤数据
- php - Datatables() - 在 MySQLi 中通过 AJAX 在 PHP 中分页