Pygame 平台碰撞检测不工作
Pygame platformer collision detection not working
我正在尝试对我的平台游戏实施碰撞检测。当我尝试 运行 游戏时,我只是从平台上掉下来,而不是在玩家击中它时停止。任何帮助或建议将不胜感激。
My full code can be found here
def collision_detect(self,x1,y1,platform):
#Stops the player from falling once they hit the platform by setting falling to false
if self.x > platform.x and self.x < platform.x2:
if self.y == platform.y:
self.yVel += 0
在逻辑和实现上有一些错误。
在你的collision_detect
中你说你把掉落的状态改成false但是你从来没有这样做过。此外,您在检查之前将 falling 设置为 true。但是先看看我的其他观点。
玩家不应该有状态 "falling" 或 "not falling"。重力一直存在,所以玩家 总是 下落。如果有一个平台可以阻挡它,那么速度就会下降到 0,就是这样。就像你实际上正在坠落,但有地板阻止你。
你不应该检查 self.y == platform.y
,因为如果你将 y 坐标增加 2 或 3,你可能 "skip" 确切的坐标,所以你真正想要的是self.y >= platform.y
.
可以完全去掉gravity
方法,只用collision_detect
方法
像这样:
def collision_detect(self, platform):
if self.x > platform.x and self.x < platform.x2:
if self.y >= platform.y:
self.yVel = 0
else:
self.yVel = 5
在你的 do
函数中尝试使用类似 self.collision_detect(platform(0, 500, 800, 20))
的东西。
我正在尝试对我的平台游戏实施碰撞检测。当我尝试 运行 游戏时,我只是从平台上掉下来,而不是在玩家击中它时停止。任何帮助或建议将不胜感激。 My full code can be found here
def collision_detect(self,x1,y1,platform):
#Stops the player from falling once they hit the platform by setting falling to false
if self.x > platform.x and self.x < platform.x2:
if self.y == platform.y:
self.yVel += 0
在逻辑和实现上有一些错误。
在你的
collision_detect
中你说你把掉落的状态改成false但是你从来没有这样做过。此外,您在检查之前将 falling 设置为 true。但是先看看我的其他观点。玩家不应该有状态 "falling" 或 "not falling"。重力一直存在,所以玩家 总是 下落。如果有一个平台可以阻挡它,那么速度就会下降到 0,就是这样。就像你实际上正在坠落,但有地板阻止你。
你不应该检查
self.y == platform.y
,因为如果你将 y 坐标增加 2 或 3,你可能 "skip" 确切的坐标,所以你真正想要的是self.y >= platform.y
.可以完全去掉
gravity
方法,只用collision_detect
方法
像这样:
def collision_detect(self, platform):
if self.x > platform.x and self.x < platform.x2:
if self.y >= platform.y:
self.yVel = 0
else:
self.yVel = 5
在你的 do
函数中尝试使用类似 self.collision_detect(platform(0, 500, 800, 20))
的东西。