如何修复Pygame中的碰撞

时间:2019-05-02 02:55:11

标签: python python-3.6

我正在尝试检测两个对象(两个图像)之间的碰撞。 我对这两个对象都有矩形,但是无法检测到碰撞。

我尝试使用rect,比较x和y位置。

import sys
import pygame
from pygame.locals import *

#init pygame
pygame.init()

window_width = 840
window_height = 650
size = (window_width, window_height)
screen = pygame.display.set_mode(size)

bg_img = pygame.image.load("img.png").convert_alpha()

crash = False
bot1x = 150
bot1y = 100
x = (window_width * 0.45)
y = (450)
clock = pygame.time.Clock()
fr = clock.tick(30)
x_speed = 0

car_img = pygame.image.load("car.png").convert_alpha()
car_img = pygame.transform.scale(car_img, (125, 175))
bot_img = pygame.image.load("bot.png").convert_alpha()
bot_img = pygame.transform.scale(bot_img, (175, 200))

def car(x, y):
    screen.blit(car_img, (x,y))

def bot(x, y):
    screen.blit(bot_img, (x,y))

car_rect = pygame.Rect(x, y, 125, 175)
bot_rect = pygame.Rect(bot1x, bot1y, 175, 200)

#game loop
while(crash==False):
    for event in pygame.event.get():
        if event.type ==  pygame.KEYDOWN:
            if event.key == K_LEFT:
                x_speed = -.9
                print("Moving Left")
            if event.key == K_RIGHT:
                x_speed = .9
                print("Moving Right")
        if event.type == pygame.KEYUP:
            if event.key == K_LEFT:
                x_speed = 0
            if event.key == K_RIGHT:
                x_speed= 0
        if event.type == pygame.QUIT:
            crash = True
    bot1y += .5

    # Move car
    x += x_speed

    if car_rect.colliderect(bot_rect):
        print("collision deceted")

    #blit images to screen
    screen.blit(bg_img, [0, 0])

    #spawn car
    car(x,y)
    bot(bot1x, bot1y)

    #flip game display
    pygame.display.flip()

#end game
pygame.quit()
quit()

我希望当两个物体彼此接触时,游戏会输出“检测到碰撞”。

谢谢

拉克兰

0 个答案:

没有答案