2017-06-21 5 views
1

私はpygameを使って、ビーチボールの画像をランダムにラップまたはバウンスするプログラムを作ろうとしています。バウンスは動作しますが、ボールをラップしようとすると、ボールがエッジに沿ってグリッチして消えます。私はそれが消えてまだ動いている後にxとyの位置を調べました。 if movement == "wrap"ブロック内Pygame ball wrapping glitch

import pygame, sys, random 
pygame.init() 
screen = pygame.display.set_mode([640, 480]) 
screen.fill([255,255,255]) 
ball = pygame.image.load('beach_ball.png') 
x = 50 
y = 50 
xspeed = 10 
yspeed = 10 
running = True 
while running: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      running = False 
    movement = random.choice(["wrap", "bounce"]) 
    pygame.time.delay(20) 
    pygame.draw.rect(screen, [255,255,255], [x, y, 90, 90], 0) 
    x = x + xspeed 
    y = y + yspeed 
    if movement == "bounce": 
     if x > screen.get_width() - 90 or x < 0: 
      xspeed = -xspeed 
     if y > screen.get_height() - 90 or y <0: 
      yspeed = -yspeed 
    if movement == "wrap": 
     if x > screen.get_width(): 
      x = -90 
     if x < 0: 
      x = screen.get_width() 
     if y > screen.get_height(): 
      y = -90 
     if y < 0: 
      y = screen.get_width() 
    screen.blit(ball, [x, y]) 
    pygame.display.flip() 

pygame.quit() 

答えて

1

、あなたはボールのpostionを変更すると、あなたもウィンドウでボールをもたらすためにコードを追加する必要があり、x = -90のようなつまり、単に行はありません。これは、コードです十分。あなたのコードが失敗した場合について議論しましょう。たとえば、ボールがウィンドウの右側に当たった場合、あなたのコードはボールのx座標を-90に設定します。次にブロック(if x < 0)の次のコードでは、コードはx = screen.get_width()になります。さらに、whileループの次の反復では、コードが潜在的にバウンスを選択し、x > screen.get_width()(ボールがまだ動いているため)の後に、xspeedを逆にする必要があります。これにより、ボールがトラップに落ちる。

基本的に、コードはバウンスやラッピングのために考慮すべき点について混乱します。しかし、ボールが内の内にある場合にのみ、これらのいずれかが発生する必要があります。しかし、ボールが外側から来ても、あなたのコードはこれらのアクションを実行します。ボールがラップするためにウィンドウの反対側にボールを置くと起こります。その場合、ボールは実際には窓から外に出ることはないので、バウンスは正しく発生します。

if movement == "wrap": 
    if x > screen.get_width() and xspeed > 0: #ball coming from within the window 
     x = -90 
    if x < 0 and xspeed < 0: 
     x = screen.get_width() 
    if y > screen.get_height() and yspeed > 0: 
     y = -90 
    if y < 0 and yspeed < 0: 
     y = screen.get_width() 
ラップを正しく動作させるには、同じことがif movement == "bounce"ブロックで行う必要があり

if movement == "bounce": 
    if (x > screen.get_width() - 90 and xspeed > 0) or (x < 0 and xspeed < 0): 
     xspeed = -xspeed 
    if (y > screen.get_height() - 90 and yspeed > 0) or (y < 0 and yspeed < 0): 
     yspeed = -yspeed 

だからあなたのような何かを行う必要があります