1
1

当たり判定 pygame

Posted at

システム

当たり判定は四角のブロックで行う、2つのブロックが存在し、二つは動くことができるとする
その時物体が重なると、必ず、どちらの角も、重なることになる

ゆえに、物体の角がもう一つの物体の範囲内またはそのもう一つの物体の角が物体の角にあれば、
物体は重なり、当たったことになる

プログラム

def collision(self, x, y, w, h):
        return (((self.rect.x < x and self.rect.w + self.rect.x > x) or (self.rect.x < x + w and self.rect.w + self.rect.x > x + w)) and 
                ((self.rect.y < y and self.rect.y + self.rect.h > y) or (self.rect.y < y + h and self.rect.y + self.rect.h > y + h)) or 
                ((x < self.rect.x and x + w > self.rect.x) or (x < self.rect.x + self.rect.w and w + x > self.rect.x + self.rect.w)) and
                ((y < self.rect.y and y + h > self.rect.y) or (y < self.rect.y + self.rect.h and h + y > self.rect.y + self.rect.h)))

物体にこの関数を持たせて、メイン処理の時、衝突を検知させたい、物体の座標をx y w hで入力し、呼び出すといい
物体が重なったときのみTrueを返す

さいごに

これはブロック型の物体でしか正しく検知されない
円形の物体の場合は、c ^ 2 = a ^ 2 + b ^ 2を使うといい

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1