皮加梅。如何使矩形在碰撞时改变方向(边界检查)

2024-04-24 16:33:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做的一项任务是让一个球在屏幕上反弹,我可以让它移动,但我的边界测试似乎不起作用:球只是朝着方向移动,而不是改变方向。所以澄清一下,我想让球在碰到屏幕边缘时改变方向。在

import sys
import pygame

SCREEN_SIZE = 750, 550
BALL_DIAMETER = 16
BALL_RADIUS = BALL_DIAMETER // 2
MAX_BALL_X = SCREEN_SIZE[0] - BALL_DIAMETER
MAX_BALL_Y = SCREEN_SIZE[1] - BALL_DIAMETER
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

LEFT = 11
RIGHT = 12
pygame.init()
clock = pygame.time.Clock()
pygame.display.init()
font = pygame.font.SysFont("impact", 20)

pygame.display.set_caption("Breakout")

screen = pygame.display.set_mode(SCREEN_SIZE)

class Ball:
    def __init__(self):
        ''' '''
        self.ball = pygame.Rect(300, 730 -
                                BALL_DIAMETER,
                                BALL_DIAMETER, BALL_DIAMETER)

    # Draw ball
    def draw_ball(self):
        pygame.draw.circle(screen,
                           WHITE, (self.ball.left
                           + BALL_RADIUS, self.ball.top +
                           BALL_RADIUS), BALL_RADIUS)

    # Updates the coordinates by adding the speed components
    def move_ball(self, x, y):
        self.xspeed = x
        self.yspeed = y
        self.ball = self.ball.move(self.xspeed, self.yspeed)


        # bounds check
        if self.ball.left <= 0:
            self.ball.left = 0
            self.xspeed = -self.xspeed
        elif self.ball.left >= MAX_BALL_X:
            self.ball.left = MAX_BALL_X
            self.xspeed = -self.xspeed
        if self.ball.top < 0:
            self.ball.top = 0
            self.yspeed = -self.yspeed
        elif self.ball.top >= MAX_BALL_Y:
            self.ball.top = MAX_BALL_Y
            self.yspeed = -self.yspeed

# shows a message on screen, for testing purposes
class Text:
    def show_message(self, message):
        self.font = pygame.font.SysFont("impact", 20)
        font = self.font.render(message,False, WHITE)
        screen.blit(font, (200, 400))


class Game:
    def __init__(self):
        ''' '''
    def run(self):
        b = Ball()
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
            keys = pygame.key.get_pressed()

            # fps lock, screen fill and method call for input
            clock.tick(60)
            screen.fill(BLACK)
            b.draw_ball()
            b.move_ball(5, -5)

            # used to keep track of various elements
            # Text().show_message("P: " + str(p))

            pygame.display.flip()

# Creates instance of the game class, and runs it
if __name__ == "__main__":
    Game().run()

Tags: selfmessagetopdefleftscreenpygamemax
1条回答
网友
1楼 · 发布于 2024-04-24 16:33:23

move_ball的唯一调用使用常量向量。 因为你从不改变调用参数,所以球只会那样移动。在

b.move_ball(5, -5)

是的,当你撞到墙上时,move_ball内的向量分量会发生变化。但是,在下一次调用时,将它们更改回原始值并将球沿原始方向移动。在

您必须初始化vectoroutsidemove_ball,然后让例程在调用时访问现有的向量。在

相关问题 更多 >