[英]Problem with slowing down ball in pong game
I've been making pong with pygame and I got the ball to bounce around the screen and on the paddles.我一直在用 pygame 打乒乓球,我让球在屏幕和球拍上弹跳。 However, the speed is too high and I want to decrease it.但是,速度太高了,我想降低它。 This is what the code looks like for the Ball object: 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
If I try to set the velocity as a float, it stops the ball completely.如果我尝试将速度设置为浮动,它会完全停止球。 Can someone help me?有人能帮我吗?
Use pygame.time.Clock
to control the frames per second and thus the game speed.使用pygame.time.Clock
来控制每秒帧数,从而控制游戏速度。
The method 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. pygame.time.Clock
object 的方法tick()
以这种方式延迟游戏,即循环的每次迭代消耗相同的时间段。 See pygame.time.Clock.tick()
:见pygame.time.Clock.tick()
:
This method should be called once per frame.此方法应每帧调用一次。
That means that the loop:这意味着循环:
clock = pygame.time.Clock() run = True while run: clock.tick(100)
runs 100 times per second.每秒运行 100 次。
Since pygame.Rect
is supposed to represent an area on the screen, a pygame.Rect
object can only store integral data.由于pygame.Rect
应该代表屏幕上的一个区域,因此pygame.Rect
object 只能存储积分数据。
The coordinates for Rect objects are all integers. Rect 对象的坐标都是整数。 [...] [...]
The fraction part of the coordinates gets lost when the movement of the object is assigned to the Rect object.当 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. 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
the coordinates and assign it to the location of the rectangle:将坐标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.