在Python中移动矩形

时间:2014-11-06 17:55:18

标签: python pygame

所以,我在Pygame中有一个矩形,它随机和对角移动。如何让它只向左,向右,向前或向后移动。此外,当遇到障碍物时,它应旋转90度并改变方向。这是我的代码:

# Main program loop
  while not done:

# Loop through any window events
for event in pygame.event.get():
    # The user clicked 'close' or hit Alt-F4
    if event.type == pygame.QUIT:
        done = True

    # The user clicked the mouse button
    # or pressed a key
    elif event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.KEYDOWN:

        # Is the ball not moving?
        if ball.change_y == 0:

            # Start in the middle of the screen at a random y location
            ball.rect.x = screen_width/2
            ball.rect.y = random.randrange(10, screen_height - 0)

            # Set a random vector
            ball.change_y = random.randrange(-5, 6)
            ball.change_x =  random.randrange(5, 10)

            # Is the ball headed left or right? Select randomly
            if( random.randrange(2) == 0 ):
                ball.change_x *= -1

1 个答案:

答案 0 :(得分:0)

您将要使用transform模块进行矩形旋转。例如,pygame.transform.rotate(ball.rect,90)。至于移动,您需要更改ball.rect.xball.rect.y的值。一个例子是:

if ball_moving_up:
    ball.rect.y += 5 #The smaller the increment the smoother it will appear
if ball_moving_down:
    ball.rect.y -= 5
if ball_moving_right:
    ball.rect.x += 5
if ball_moving_left:
    ball.rect.x -= 5

此外,您还希望在每次增量后更新背景,否则您的矩形将显示为实线。

如果您有任何疑问,请发表评论。 希望这有帮助。