衝突検出は幅広いトピックです。特に、コレクションがどちらの側から発生したかを知りたい場合はそうです。(プラットフォーマーの一般的なアプローチは、この例のように、水平方向の動きと垂直方向の動きに対して 1 回ずつ、衝突検出を 2 回行うことです)。
Rect
が別の の下部と衝突するかどうかだけを知りたい場合はRect
、次のコード例が出発点として適切です。
def collide_top(a, b):
return a.top <= b.bottom <= a.bottom and (a.left <= b.left <= a.right or b.left <= a.left <= b.right)
def collide_bottom(a, b):
return a.bottom >= b.top >= a.top and (a.left <= b.left <= a.right or b.left <= a.left <= b.right)
def collide_left(a, b):
return a.left <= b.right <= a.right and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom)
def collide_right(a, b):
return a.right >= b.left >= a.left and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom)
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
center = Rect((100, 100, 100, 100))
player = Rect((10, 0, 75, 75))
move = {K_UP: ( 0, -1),
K_DOWN: ( 0, 1),
K_LEFT: (-1, 0),
K_RIGHT: ( 1, 0)}
while True:
screen.fill((0, 0 ,0))
pressed = pygame.key.get_pressed()
for d in [m for (k, m) in move.items() if pressed[k]]:
player.move_ip(*d)
pygame.draw.rect(screen, (120, 0, 120), center, 3)
pygame.draw.rect(screen, (0, 200, 55), player, 2)
# check if 'player' collides with the bottom of 'center'
print collide_bottom(center, player)
pygame.display.flip()
if pygame.event.get(QUIT): break
pygame.event.poll()
clock.tick(60)

(この図ではplayer
、 は の下部と左側に衝突しますがcenter
、上部または右側には衝突しません)
さらにいくつかの質問:
ある四角形が別の四角形の中に完全に入っているとどうなりますか? この場合、すべてのエッジと衝突しますか、それともまったく衝突しませんか?
あなたのコメントに応えて:
衝突チェックを単に変更することができます
def collide_top(a, b):
return a.top == b.bottom and (a.left <= b.left <= a.right or b.left <= a.left <= b.right)
def collide_bottom(a, b):
return a.bottom == b.top and (a.left <= b.left <= a.right or b.left <= a.left <= b.right)
def collide_left(a, b):
return a.left == b.right and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom)
def collide_right(a, b):
return a.right == b.left and (a.top <= b.top <= a.bottom or b.top <= a.top <= b.bottom)