在pygame中的墙碰撞

时间:2017-12-13 23:11:24

标签: python pygame collision

我试图让碰撞工作,但是当两个矩形碰撞时,它们会相互进入,但我希望第二个矩形像墙一样。有人知道如何解决这个问题吗?或者是否有更好的方法可以为我的游戏添加碰撞?这就是我现在所拥有的。

import pygame

pygame.init()
screen = pygame.display.set_mode((1000, 800))
pygame.display.set_caption("Squarey")
done = False
is_red = True
x = 30
y = 30
x2 = 100
y2 = 30
clock = pygame.time.Clock()
WHITE = (255,255,255)
RED = (255,0,0)

charImg = pygame.image.load('character.png')



rect1 = pygame.Rect(30, 30, 60, 60)

rect2 = pygame.Rect(100, 100, 60, 60)

x_change = 0
y_change = 0

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True


#movement
      #left
    if event.type == pygame.KEYDOWN:
      if event.key == pygame.K_LEFT:
        x_change = -5
        y_change = 0

        #right
      elif event.key == pygame.K_RIGHT:
        x_change = 5
        y_change = 0
      #key release left and right
    if event.type == pygame.KEYUP:
      if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
        x_change = 0
        y_change = 0


      #up    
    if event.type == pygame.KEYDOWN:
      if event.key == pygame.K_UP:
        y_change = -5
        x_change = 0


        #down
      elif event.key == pygame.K_DOWN:
        y_change = 5
        x_change = 0


      #key release up and down
    if event.type == pygame.KEYUP:
      if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
        y_change = 0
        x_change = 0 
    rect1.x = rect1.x + x_change
    rect1.y = rect1.y + y_change

    screen.fill((0, 0, 0))

    pygame.draw.rect(screen, WHITE, rect1)
    pygame.draw.rect(screen, RED, rect2)

    if rect1.bottom > screen.get_rect().bottom:
      rect1.center = screen.get_rect().center

    #if rect1.colliderect(rect2):
    if rect1.colliderect(rect2):
      #print("Collision !!")

      rect1.x = rect1.x - x_change
      rect1.y = rect1.y - y_change

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

1 个答案:

答案 0 :(得分:0)

您正在绘制矩形,然后将它们彼此碰到一起放回原处,以便它们彼此移动一会儿。计算完成后,请确保进行所有绘图。