2017-09-23 20 views
0

私は、プレイヤーがジャンプして左右に動くことができるpygameのplatformerを持っています。プレーヤがプラットフォームと衝突しているかどうかをテストするために、pygame.rect.colliderect()関数を使用します。私が抱えている問題は、プレイヤーが彼とプラットホームを同時に殺すブロックにいるとき、殺しブロックがプラットホームの左にあるなら、彼は死ぬだろうということです。プラットフォームの右側にある場合、彼は生きるでしょう。 私は、衝突をテストするためのよりよい方法があるかどうか、あるいは自分でそのような機能を作らなければならないかどうかを知りたいと思います。より良い方法pygame.rect.colliderect()

プレーヤーはピンク、プラットフォームは白、死のブロックは赤です。プレイヤーは最初の画像で死ぬが、2番目の画像で死ぬ。

enter image description hereenter image description here

これは私の現在のコードです:

class Player(Entity): 
(other things in the Player class that are irrelevant) 
def update(self): 
    self.xvel = 0 
    keys = pygame.key.get_pressed() 
    if keys[pygame.K_w] and self.onfloor: self.yvel = -2 
    if keys[pygame.K_a]: self.xvel = -1 
    if keys[pygame.K_s]: pass 
    if keys[pygame.K_d]: self.xvel = 1 
    if not self.onfloor and self.yvel < 10: 
     self.yvel += .05 
    self.move(self.xvel, 0) 
    self.move(0, self.yvel) 
def move(self, xvel, yvel): 
    self.rect.x += xvel 
    self.rect.y += yvel 
    self.onfloor = False 
    for thing in entities: # entities is a list of all entities, thing.rect is the pygame.rect.Rect instance for that entity 
     if thing != self: 
      if self.rect.colliderect(thing.rect): 
       if isinstance(thing, End): self.won = True 
       if isinstance(thing, Death): self.lost = True 
       if yvel < 0: 
        self.rect.top = thing.rect.bottom 
        self.yvel = 0 
       if xvel < 0: self.rect.left = thing.rect.right 
       if yvel > 0: 
        self.rect.bottom = thing.rect.top 
        self.onfloor = True 
       if xvel > 0: self.rect.right = thing.rect.left 

私は自分の関数を作ってみましたが、それは動作しませんでした。これは私がやったことです:

def entitycollide(self, entity): 
sx1, sx2, sy1, sy2 = self.rect.left, self.rect.right, self.rect.top, self.rect.bottom 
ex1, ex2, ey1, ey2 = entity.rect.left, entity.rect.right, entity.rect.top, entity.rect.bottom 
if ((sx1 < ex1 < sx2) or (sx1 < ex2 < sx2)) and ((sy1 < ey1 < sy2) or (sy1 < ey2 < sy2)): 
    return True 
else: return False 
+0

「デスブロック」がどのプラットフォームにも隣接していないとどうなりますか? –

+0

プレイヤーがプラットフォームに隣接していない死ブロックまたは2死ブロックにいる場合、彼は死ぬだろう。 – SnootierBaBoon

答えて

0

一般的な答えは、2回する必要があります。最初にcolliderectが識別するすべてのオブジェクト(またはその値がrect.topのすべてのものがプレーヤの下にあるものとして識別するすべてのオブジェクト)を収集します。そして、一度にすべてのオブジェクトに反応します。

ここでは、プレイヤーが立っている一番左側のブロックを保存するだけで十分でしょう(これはおそらくさらに考慮すると変更される可能性があります。entities)。すべての候補を検討した後、保存されたブロックのタイプに反応します。

+0

移動した後にプレイヤーと衝突するすべてのエンティティを取得した場合、プレイヤーは壁と死のブロックに同時に遭遇すると死にます。これは変です。私はちょうどプレーヤーが同時にプラットフォームと死のブロックに実行されている場合、死ぬことはないと言ってそれを修正します。 – SnootierBaBoon

+0

'self.lost == Trueで、同じ方向にプラットフォームに衝突したかどうかを確認するもの):self.lost = False' – SnootierBaBoon

+0

@SnootierBaBoon:私はすでに、プレーヤーの下に。 'self.lost'をリセットすることについては、あなたが触れているときに0 HPで生き残ることができるように、間違って設定しないことを考えてください(' nDeathならばnPlatform:self.lost = True'のようなもの)壁。"。 –