簡體   English   中英

為什么我的 pygame 對象會振動而不是平滑移動?

[英]Why does my pygame object vibrate instead of moving smoothly?

首先,我對編碼很陌生,所以如果我的代碼看起來很糟糕,這就是為什么

我正在嘗試使用 PyGame 生成 10 個在隨機位置生成並在隨機向量中移動的球。 當每個球擊中屏幕邊緣時,它會反彈回來。

我在下面的代碼的問題是球確實產卵很好,球確實從窗口彈回了很好,但球僅沿 x 軸(左右)移動但在 y 軸上振動(上和下)。 我不知道為什么會這樣。

我的代碼如下:

from random import randint, choice
import pygame
pygame.init()

## -- set constants
white = [255, 255, 255]
black = [0, 0, 0]
grey = [255/2, 255/2, 255/2]

ball_fill = white # colour of balls or circle objects
ball_line_colour = ball_fill # border and fill of same colour

n_balls = 10 # number of balls on a window
ball_radius = 12 # size of balls in pixels

velocity = vel = {
    "x": randint(-2, 3),
    "y": randint(-2, 3)
    } # must range from -a to +b; otherwise will only move rightward and upward

## -- set display window

win_width = 800 # pixels; width of screen
win_height = 600

## -- Define the boundaries, that is, the points at which the balls would bounce back without going out of the window

boundary_location = ['up', 'down', 'left', 'right']
boundary_coord = [ball_radius, (win_height - ball_radius),
                  ball_radius, (win_width - ball_radius)]

boundary = dict(zip(boundary_location, boundary_coord))

## -- Define balls
class Ball():
    def __init__(self):
        self.x = 0
        self.y = 0
        self.change_x = 0
        self.change_y = 0

def make_ball():
    """
    Function to make a new circle or ball
    """

    ball = Ball()
    # spawn points of balls, so that the balls do not overlap when they spawn

    x = randint(boundary["left"], boundary["right"])

    ball.x = choice([n for n in range(int(boundary["left"]), int(boundary["right"]))
        if n not in range(x - ball_radius, x + ball_radius)])

    y = randint(boundary["up"], boundary["down"])

    ball.y = choice([n for n in range(int(boundary["up"]), int(boundary["down"]))
        if n not in range(y - ball_radius, y + ball_radius)])

    # Speed and direction of rectangle

    ball.change_x = vel["x"]
    ball.change_y = vel["y"]

    return ball

# Set the height and width of the screen

win_dimen = [win_width, win_height]
win = pygame.display.set_mode(win_dimen)

pygame.display.set_caption("Multiple Object Tracking")

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

ball_list = []

for i in range(n_balls):
    ball = make_ball()
    ball_list.append(ball)
    i -= 1

# -------- Main Program Loop -----------
while not done:
    # --- Event Processing
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN:
    # Space bar or esc to exit
            if event.key == pygame.K_SPACE or event.key == pygame.K_ESCAPE:
                done = True

    # --- Logic
    for ball in ball_list:
        # Move the ball's positions
        ball.x += ball.change_x
        ball.y += ball.change_y

        # Bounce the ball if needed
        if ball.y > boundary["up"] or ball.y < boundary["down"]:
            ball.change_y *= -1
        if ball.x > boundary["right"] or ball.x < boundary["left"]:
            ball.change_x *= -1

    # Set the screen background
    win.fill(grey)

    # Draw the balls
    for ball in ball_list:
        pygame.draw.circle(win, white, [ball.x, ball.y], ball_radius)

    clock.tick(60)

    # Update the screen
    pygame.display.flip()

# Close everything down
pygame.quit()

我的下一步是讓球相互彈開,以防有人想知道

檢查向上/向下邊界的邏輯是相反的,因此發生振動是因為球不斷出界並且在每一幀上都反轉了它們的 y 速度。 如果您更改行:

if ball.y > boundary["up"] or ball.y < boundary["down"]:

到:

if ball.y < boundary["up"] or ball.y > boundary["down"]:

你會一切都好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM