2016-04-02 24 views
-1
import pygame 

BLACK = pygame.color.Color('Black') 
YELLOW = pygame.color.Color('Yellow') 
BLUE = pygame.color.Color('Blue') 

pygame.init() 
screen = pygame.display.set_mode([700,500]) 
screen_rect = screen.get_rect() 

pygame.display.set_caption("Trial to make PONG") 

blue_rect = pygame.Rect(10, 250, 20, 60) 
yellow_rect = pygame.Rect(670, 250, 20, 60) 
ball_rect = pygame.Rect(50, 50, 50, 50) 

ball_x_speed = 5 
ball_y_speed = 5 

clock = pygame.time.Clock() 

done = False 
while not done: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      done = True 

    # check all pressed keys and move the paddles 
    pressed = pygame.key.get_pressed() 
    if pressed[pygame.K_UP]: blue_rect.move_ip(0, -5) 
    if pressed[pygame.K_DOWN]: blue_rect.move_ip(0, 5) 
    if pressed[pygame.K_w]: yellow_rect.move_ip(0, -5) 
    if pressed[pygame.K_s]: yellow_rect.move_ip(0, 5) 

    # ensure paddles stay on screen 
    blue_rect.clamp_ip(screen_rect) 
    yellow_rect.clamp_ip(screen_rect) 

    # move the ball 
    ball_rect.move_ip(ball_x_speed, ball_y_speed) 

    # check if the ball needs to change direction 
    if ball_rect.x + ball_rect.width > screen_rect.width or ball_rect.x < 0: 
     ball_x_speed = ball_x_speed * -1 
    if ball_rect.y + ball_rect.height> screen_rect.height or ball_rect.y < 0: 
     ball_y_speed = ball_y_speed * -1 


    # draw everything 
    screen.fill(BLACK) 
    pygame.draw.ellipse(screen, BLUE, ball_rect) 
    pygame.draw.rect(screen,BLUE, blue_rect) 
    pygame.draw.rect(screen,YELLOW, yellow_rect) 
    pygame.display.flip() 
    clock.tick(60) 

pygame.quit() 

私はゲームで2つのパドルを持ち、ボールはバウンドしています。私はボールがパドルに当たったときに衝突点を作ろうとしました。私はポンを作り直そうとしています。衝突ポイントは機能しませんでした(おそらく私はそれを正しく構成しなかったため)。ボールをパドルから跳ね返す方法

パドル(矩形の青と黄色)とボール(ball_rect)の間にどのようにして衝突ポイントを作ってボールがパドルから跳ね返るようにすることができますか?

+0

あなたは、背壁から跳ね返ってくるボールを扱っているようです。パドルもチェックする必要があります。このコードは、y座標を考慮する必要があることを除いて、ボールの壁のチェックと多少似ています。 – sbochins

答えて

1

これは動作するはずです:

# Inside the main loop. 
if ball_rect.collidelist([blue_rect, yellow_rect]) > -1: 
    ball_x_speed = -ball_x_speed 

はそれが役に立てば幸い!

+0

ありがとうございます。あなたは揺れる! – HALLOPEOPLE

+0

@HALLOPEOPLEあなたは大歓迎です:-) – cdonts

関連する問題