简体   繁体   中英

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. However, the speed is too high and I want to decrease it. This is what the code looks like for the 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.

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. See 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.


Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. [...]

The fraction part of the coordinates gets lost when the movement of the object is assigned to the 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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM