How to draw a moving circle in Pygame with a small angle at a low speed and blinking?

后端 未结 1 400
时光说笑
时光说笑 2020-12-21 17:25

The code below moves two balls on the screen. The first one is moved with an angle of 10 degree at a low speed with a good drawing quality. The second ball is moved with an

相关标签:
1条回答
  • 2020-12-21 18:18

    The issue is caused, because pygame.Rect stores integral coordinates:

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

    The fraction component of delta_x and delta_y is lost at self.rect.move(delta_x, delta_y).

    You have to use floating point numbers for the computation. Add an attribute self.pos, which is a tupe with 2 components an stores the center point of a ball:

    self.pos = self.rect.center
    

    Compute the position with the maximum floating point accuracy:

    delta_x = self.speed * math.cos(self.angle)
    delta_y = self.speed * math.sin(self.angle)
    self.pos = (self.pos[0] + delta_x, self.pos[1] + delta_y)   
    

    Update the self.rect.center by the round()ed position.

    self.rect.center = round(self.pos[0]), round(self.pos[1])
    

    self.pos is the "internal" position and responsible for the exact computation of the position. self.rect.center is the integral position and responsible to draw the ball. self.pos slightly changes in each frame. self.rect.center changes only if the a component of the coordinate has changed by 1.

    Class Ball:

    class Ball():
        def __init__(self,
                     screen,
                     color,
                     radius,
                     startX,
                     startY,
                     speed,
                     angle=45):
            super().__init__()
            self.screen = screen
            self.color = color
            rectSize = radius * 2
            self.rect = pygame.Rect(startX, startY, rectSize, rectSize)
            self.speed = speed
            self.angle = math.radians(angle)
            self.pos = self.rect.center
    
        def update(self):
            delta_x = self.speed * math.cos(self.angle)
            delta_y = self.speed * math.sin(self.angle)
            self.pos = (self.pos[0] + delta_x, self.pos[1] + delta_y)
    
            self.rect.center = round(self.pos[0]), round(self.pos[1])
    
            if self.rect.right >= self.screen.get_width() or self.rect.left <= 0:
                self.angle = math.pi - self.angle
    
            if self.rect.top <= 0 or self.rect.bottom >= self.screen.get_height():
                self.angle = -self.angle
    
        def draw(self):
            '''
            Draw our ball to the screen with position information.
            '''
            pygame.draw.circle(self.screen, self.color, self.rect.center, int(self.rect.width / 2))
    

    With this solution you can scale up the flops per second (clock.tick()) and scale down the speed by the same scale. This leads to a smooth movement without blinking.

    0 讨论(0)
提交回复
热议问题