簡體   English   中英

在乒乓球比賽中放慢球的問題

[英]Problem with slowing down ball in pong game

我一直在用 pygame 打乒乓球,我讓球在屏幕和球拍上彈跳。 但是,速度太高了,我想降低它。 Ball object 的代碼如下所示:

import pygame as pg
BLACK = (0, 0, 0)


class Ball(pg.sprite.Sprite):
    def __init__(self, color, width, height, radius):
        super().__init__()

        self.x_vel = 1
        self.y_vel = 1
        self.image = pg.Surface([width * 2, height * 2])
        self.image.fill(BLACK)
        self.image.set_colorkey(BLACK)

        pg.draw.circle(self.image, color, center=[width, height], radius=radius)

        self.rect = self.image.get_rect()

    def update_ball(self):
        self.rect.x += self.x_vel
        self.rect.y += self.y_vel

如果我嘗試將速度設置為浮動,它會完全停止球。 有人能幫我嗎?

使用pygame.time.Clock來控制每秒幀數,從而控制游戲速度。

pygame.time.Clock object 的方法tick()以這種方式延遲游戲,即循環的每次迭代消耗相同的時間段。 pygame.time.Clock.tick()

此方法應每幀調用一次。

這意味着循環:

 clock = pygame.time.Clock() run = True while run: clock.tick(100)

每秒運行 100 次。


由於pygame.Rect應該代表屏幕上的一個區域,因此pygame.Rect object 只能存儲積分數據。

Rect 對象的坐標都是整數。 [...]

當 object 的運動分配給Rect object 時,坐標的小數部分會丟失。

If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect object.將坐標round並將其分配給矩形的位置:

class Ball(pg.sprite.Sprite):
    def __init__(self, color, width, height, radius):
        # [...]

        self.rect = self.image.get_rect()
        self.x = self.rect.x
        self.y = self.rect.y

    def update_ball(self):
        self.x += self.x_vel
        self.y += self.y_vel
        self.rect.x = round(self.x)
        self.rect.y = round(self.y)

暫無
暫無

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

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