2

この質問にはコードは必要ありませんが、他の場所で答えが見つからなかった問題です。

長方形の端でのみ Pygame の長方形の衝突をテストするにはどうすればよいですか? 私はhttp://www.pygame.org/docs/ref/rect.htmlを見て、答えがあるように感じましたが、それを見ることができません。これは非常に重要であり、これが簡単な修正であり、答えられることを願っています。

if <rectname>.colliderect.bottom(<otherRect>):
    output = True

^ うまくいきませんが、答えは似ているのではないかと思います。誰かが助けてくれるなら、事前に感謝します!

4

1 に答える 1

1

衝突検出は幅広いトピックです。特に、コレクションがどちらの側から発生したかを知りたい場合はそうです。(プラットフォーマーの一般的なアプローチは、この例のように、水平方向の動きと垂直方向の動きに対して 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)
于 2013-07-24T07:54:49.693 に答える