Python PyGame碰撞只在矩形的一侧起作用

Python PyGame碰撞只在矩形的一侧起作用,python,pygame,collision-detection,Python,Pygame,Collision Detection,我只是尝试了一些关于碰撞的东西,找到了检查矩形一边和另一边的方法 我有以下问题: 如果我将我的游戏角色(粉色框)从左侧移动到对象上,我的游戏角色只会在其中移动: 如果我来自另一边,一切正常,我的游戏角色停止 我的意思是说,我需要双方使用相同的代码,但必须将双方从if not player\u rect.left==other\u rect.right:更改为if not player\u rect.right==other\u rect.left:。但这对一方不起作用 import pyga

我只是尝试了一些关于碰撞的东西,找到了检查矩形一边和另一边的方法

我有以下问题:

如果我将我的游戏角色(粉色框)从左侧移动到对象上,我的游戏角色只会在其中移动:

如果我来自另一边,一切正常,我的游戏角色停止

我的意思是说,我需要双方使用相同的代码,但必须将双方从
if not player\u rect.left==other\u rect.right:
更改为
if not player\u rect.right==other\u rect.left:
。但这对一方不起作用

import pygame
import sys

pygame.init()

clock = pygame.time.Clock()
window = pygame.display.set_mode([1200, 800])
pygame.display.set_caption("Collision Test")

x = 300
y = 300
width = 48
height = 96
velocity = 5

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        is_pressed = pygame.key.get_pressed()
        player_rect = pygame.Rect(x, y, width, height)
        other_rect = pygame.Rect(400, 300, 50, 50)

        if is_pressed[pygame.K_d]:
            if not player_rect.right == other_rect.left:
                x += velocity
        if is_pressed[pygame.K_a]:
            if not player_rect.left == other_rect.right:
                x -= velocity

    window.fill((100, 150, 50))
    pygame.draw.rect(window, (255, 50, 100), player_rect)
    pygame.draw.rect(window, (255, 100, 50), other_rect)
    pygame.display.update()
    clock.tick(60)

使用

移动对象并测试矩形是否发生碰撞。检测到碰撞时,根据移动方向更改对象的位置:

is_pressed=pygame.key.get_pressed()
向右移动=按下[pygame.K\u d]
向左移动=按下[pygame.K\u a]
如果向右移动(u):
x+=速度
如果向左移动,请执行以下操作:
x-=速度
player_rect=pygame.rect(x,y,宽度,高度)
other_rect=pygame.rect(400,300,50,50)
如果玩家正确碰撞正确(其他正确):
如果向右移动(u):
玩家右=其他玩家左
x=玩家右左
如果向左移动,请执行以下操作:
玩家左=其他右
x=玩家右左
为了平稳移动,您必须在应用程序循环而不是事件循环中执行evaluate
pygame.key.get\u pressed()

另见

导入pygame
导入系统
pygame.init()
clock=pygame.time.clock()
window=pygame.display.set_模式([1200800])
pygame.display.set_标题(“碰撞测试”)
x=300
y=300
宽度=48
高度=96
速度=5
运行=真
运行时:
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
sys.exit()
按下按钮=pygame.key.get\u按下()
向右移动=按下[pygame.K\u d]
向左移动=按下[pygame.K\u a]
如果向右移动(u):
x+=速度
如果向左移动,请执行以下操作:
x-=速度
player_rect=pygame.rect(x,y,宽度,高度)
other_rect=pygame.rect(400,300,50,50)
如果玩家正确碰撞正确(其他正确):
如果向右移动(u):
玩家右=其他玩家左
x=玩家右左
如果向左移动,请执行以下操作:
玩家左=其他右
x=玩家右左
窗口填充((10015050))
pygame.draw.rect(窗口,(255,50,100),玩家\u rect)
pygame.draw.rect(窗口,(255,100,50),其他矩形)
pygame.display.update()
时钟滴答(60)

现在我如何实现跳跃或重力。当然,这应该适用于上面和下面的碰撞。我已经尝试了很多东西,但我找不到解决办法。我加了一个跳跃,但是我在长方形上,当我试着往下跑的时候,我再也没有摔倒了。请帮忙me@Max如果你有新问题,请回答。评论部分不用于询问其他问题。也不要扩展这个问题,你将不得不提出一个全新的问题。请在新问题中分享您到目前为止尝试过的内容。好的,对不起。但上面说我需要再等两天才能问一个新问题。@Max你确定吗。即使这个问题被投票表决通过,并且得到了公认的答案,你还需要等待吗?“你已经达到了问题的极限,看起来你可能需要休息一下-休息一下,然后很快回来!你最近问了两个问题,其中一些问题没有被……很好地接受。”看起来是这样的:/