在乒乓球比赛中放慢球速的问题
Problem with slowing down ball in pong game
我一直在用 pygame 打乒乓球,我让球在屏幕和球拍上弹跳。但是,速度太高了,我想降低它。这是 Ball 对象的代码:
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
控制每秒帧数,从而控制游戏速度。
方法tick()
of a pygame.time.Clock
object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick()
:
This method should be called once per frame.
这意味着循环:
clock = pygame.time.Clock()
run = True
while run:
clock.tick(100)
每秒运行 100 次。
由于pygame.Rect
应该表示屏幕上的一个区域,因此pygame.Rect
对象只能存储整数数据。
The coordinates for Rect objects are all integers. [...]
当对象的运动分配给 Rect 对象时,坐标的小数部分丢失。
如果要以浮点精度存储对象位置,则必须将对象的位置分别存储在单独的变量和属性中,并同步 pygame.Rect
对象。 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)
我一直在用 pygame 打乒乓球,我让球在屏幕和球拍上弹跳。但是,速度太高了,我想降低它。这是 Ball 对象的代码:
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
控制每秒帧数,从而控制游戏速度。
方法tick()
of a pygame.time.Clock
object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick()
:
This method should be called once per frame.
这意味着循环:
clock = pygame.time.Clock() run = True while run: clock.tick(100)
每秒运行 100 次。
由于pygame.Rect
应该表示屏幕上的一个区域,因此pygame.Rect
对象只能存储整数数据。
The coordinates for Rect objects are all integers. [...]
当对象的运动分配给 Rect 对象时,坐标的小数部分丢失。
如果要以浮点精度存储对象位置,则必须将对象的位置分别存储在单独的变量和属性中,并同步 pygame.Rect
对象。 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)