How To Draw A Moving Circle In Pygame With A Small Angle At A Low Speed And Blinking?
Solution 1:
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:
classBall():
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
defupdate(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 <= 0or self.rect.bottom >= self.screen.get_height():
self.angle = -self.angle
defdraw(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.
Post a Comment for "How To Draw A Moving Circle In Pygame With A Small Angle At A Low Speed And Blinking?"