如何让球从桨上弹开 [英] How to make ball bounce off paddle

查看:53
本文介绍了如何让球从桨上弹开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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()

我在游戏中有两个桨,一个球在四处弹跳.当球击中球拍时,我尝试制作一个碰撞点.我正在尝试重新创建乒乓球.碰撞点不起作用(可能是因为我没有正确构建它).

I have two paddles in the game and a ball is bouncing around. I tried making a collide point when the ball hit's the paddle. Im trying to recreate pong. The collide point didn't work (maybe because I didn't structure it right).

我想知道如何在球拍(蓝色和黄色矩形)和球(ball_rect)之间建立一个碰撞点,以便球从球拍上反弹?

I was wondering how can I make a collide point between the paddle (rectangle Blue and Yellow) and the ball (ball_rect) so that the ball bounces off the paddle?

推荐答案

这应该有效:

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

希望有帮助!

这篇关于如何让球从桨上弹开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆