python - PyGame 碰撞响应错误
问题描述
我的问题:
当我在 PyGame 中处理碰撞响应时,一切正常,直到我与对角线碰撞(xvel 和 yvel != 0)。如果我在检查它们各自的轴时有一个 print("x") 和 print("y") 语句,我会得到如下信息:
很明显,该错误是由中间的随机“x”引起的,这导致代码表现得好像字符与 x 轴上的某物发生碰撞,而实际上它是 y 轴。所以这真的是我的问题,为什么会发生这种情况?
这是我的碰撞响应函数:
def collide(self, direction):
hits = pg.sprite.spritecollide(self, all_sprites_wall, False, rectconverter)
if direction == "x":
if hits:
print("x")
if self.vx > 0:
self.hitboxrect.right = hits[0].hitboxrect.left
self.x = self.hitboxrect.right - self.rect.width - camera.camera.x
if self.vx < 0:
self.hitboxrect.left = hits[0].hitboxrect.right
self.x = self.hitboxrect.left - self.rect.width + self.hitboxrect.width - camera.camera.x
self.rect.x = self.x
if direction == "y":
if hits:
print("y")
if self.vy > 0:
self.hitboxrect.bottom = hits[0].hitboxrect.top
self.y = self.hitboxrect.bottom - self.rect.height - camera.camera.y
if self.vy < 0:
self.hitboxrect.top = hits[0].hitboxrect.bottom
self.y = self.hitboxrect.top - self.rect.height + self.hitboxrect.height - camera.camera.y
self.rect.y = self.y
球员更新功能:
def update(self):
self.move("x")
self.hitboxrect.x = self.x + camera.camera.x
self.rect.x = self.x
self.collide("x")
self.move("y")
self.hitboxrect.y = self.y + camera.camera.y + self.rect.height - self.hitboxrect.height
self.rect.y = self.y
self.collide("y")
球员移动功能:
def move(self, direction):
if direction == "x":
self.x += self.vx * dt
if direction == "y":
self.y += self.vy * dt
解决方案
不知何故,我自己找到了答案:
问题在于我正在添加和减去相机值,因此通过删除相机 x 和 y 值,错误消失了。老实说,我不确定为什么这解决了它,但我会接受。以下是任何好奇的人现在的代码外观:
def collide(self, direction):
hits = pg.sprite.spritecollide(self, all_sprites_wall, False, rectconverter)
if direction == "x":
if hits:
print("x")
if self.vx > 0:
self.x = hits[0].hitboxrect.left - self.rect.width
self.hitboxrect.right = hits[0].hitboxrect.left
if self.vx < 0:
self.x = hits[0].hitboxrect.right - self.rect.width + self.hitboxrect.width
self.hitboxrect.left = hits[0].hitboxrect.right
self.rect.x = self.x
if direction == "y":
if hits:
print("y")
if self.vy > 0:
self.y = hits[0].hitboxrect.top - self.rect.height
self.hitboxrect.bottom = hits[0].hitboxrect.top
if self.vy < 0:
self.y = hits[0].hitboxrect.bottom - self.rect.height + self.hitboxrect.height
self.hitboxrect.top = hits[0].hitboxrect.bottom
self.rect.y = self.y
推荐阅读
- c - C中数据的抛物线过滤
- laravel - Laravel 中的动态表单字段不应具有相同的值
- excel - EXcel - 无法打开 URL:无法下载您请求的信息
- google-cloud-platform - Google Cloud Text To Speech API 强制发音为单词
- java - 错误:链接文件资源失败。AAPT 错误
- typo3 - config.sys_language_mode = strict 不会从设置为“所有语言”的记录中获取文件
- css - 打印中断引导布局
- javascript - 在 div 上制作图像,如邮票
- c++ - cocos2d-x 和 cocos2d-iphone 如何保证单批绘制 2 个精灵的正确 zorder(occlusion)?
- javascript - 未捕获的类型错误:elasticsearch.Client 不是构造函数 elasticsearch.js