【问题标题】:Python collision detection between rectangles矩形之间的Python碰撞检测
【发布时间】:2014-05-15 17:57:18
【问题描述】:

我试图弄清楚如何在矩形之间进行一些基本的碰撞检测。 它在我的敌人矩形的所有面上工作,除了左侧。虽然似乎检测到了碰撞,但我的玩家正在朝着与我的指示相反的方向移动。

#!/usr/bin/python

import pygame
from random import randrange
pygame.init()

BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
color = GREEN

w = 800
h = 600
size = (w, h)


screen = pygame.display.set_mode(size)
pygame.display.set_caption("Cool Window")



done = False

clock = pygame.time.Clock()
pos_x = 0
pos_y = 0

enemy_pos_x = w/2
enemy_pos_y = h/2
last_move = "none"



while not done:

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



    if(event.type==pygame.KEYDOWN):
        if(event.key == pygame.K_ESCAPE):
            done = True
        if(event.key == pygame.K_LEFT):
            pos_x -= 5
            last_move = "left"
            print 'Posx: %s.\n' % pos_x

        if(event.key == pygame.K_RIGHT):
            pos_x += 5
            las_move = "right"
            print 'Posx: %s.\n' % pos_x

        if(event.key == pygame.K_UP):
            pos_y -= 5
            last_move = "up"
            print 'Posy: %s.\n' % pos_y

        if(event.key == pygame.K_DOWN):
            pos_y += 5
            last_move = "down"
            print 'Posy: %s.\n' % pos_y

    if pos_x+40 > 800:
        pos_x -= 5
    if pos_x < 0:
        pos_x += 5

    if pos_y+40 > 600:
        pos_y -= 5
    if pos_y < 0:
        pos_y += 5

    #collision with enemy
    if (pos_x+40 >= enemy_pos_x ) & (pos_y+40 >= enemy_pos_y) & (pos_x <= enemy_pos_x+40) & (pos_y <= enemy_pos_y+40):

        print 'Collision \n'
        if last_move == "left" :
            pos_x += 5
        if last_move == "right" :
            pos_x -= 5
        if last_move == "up" :
            pos_y += 5
        if last_move == "down" :
            pos_y -= 5





    screen.fill(BLACK)

    #Draw

    pygame.draw.rect(screen, WHITE, [enemy_pos_x, enemy_pos_y, 40, 40])
    pygame.draw.rect(screen, color, [pos_x, pos_y, 40, 40])



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


pygame.quit()

【问题讨论】:

标签: python pygame collision


【解决方案1】:

我自己也遇到了这个问题,所以我做了一些研究,发现了一个很好的 JavaScript 代码,所以我把它翻译成 python,这是布局:

if rect_1_x < rect_2_x + rect_1_width and rect_1_x + rect_2_width > rect_2_x and rect_1_y < rect_2_y + rect_1_height and rect_2_height + rect_1_y > rect_2_y:

#now type whatever code you want to be activated when the rectangles touch

这是通过检测第一个矩形 (rect_1) 的任何边缘是否与第二个矩形 (rect_2) 的任何边缘接触来实现的。 这并不能解决传递问题,它只是更好地计算碰撞。

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 2023-01-26
    • 2014-05-05
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多