Why does my second called ball in pygame flicker?

时间:2017-08-05 11:12:12

标签: python python-2.7 class pygame instance

I made a class Ball with two instances: ballOne and ballTwo. When I call ballTwo.update() and then ballOne.update(), the last called ball sometimes disappears on some frames, like it sometimes flickers on and off. Can someone please help?

import pygame, sys


pygame.init()

red = (255,0,0)
black = (0,0,0)
white = (255,255,255)
blue = (0,0,255)
green = (0,255,0)

pygame.mouse.set_visible(0)
clock = pygame.time.Clock()

displaySize = (800,600)

screen = pygame.display.set_mode(displaySize)

g = 50
dt = 0.05

Cd = 0.01
m = 5

class ball:
    def __init__(self, x, y, vx, vy, r,ax,ay, color):

        self.Fx = 0
        self.Fy = 0

        self.Dx = 0
        self.Dy = 0

        self.ay = ay
        self.ax = ax

        self.x = x
        self.y = y
        self.r = r
        self.color = color

        self.vx = vx
        self.vy = vy



    def update(self):

        self.x, self.y = self.physics()
        pygame.draw.circle(screen, self.color, (int(round(self.x)),int(round(self.y))), self.r)
        pygame.display.update()





    def physics(self):


        self.x +=self.vx*dt
        self.y +=self.vy*dt

        self.vy += self.ay*dt
        self.vx += self.ax*dt

        self.ay = self.Fy/m
        self.ax = self.Fx/m

        self.Fy = m*g - self.Dy
        self.Fx = -self.Dx

        self.Dy = Cd*self.vy*abs(self.vy)
        self.Dx = Cd*self.vx*abs(self.vx)

        if self.x <= self.r:
            self.vx *= -0.7

        if self.x >= displaySize[0]- self.r:
            self.vx *= -0.7

        if self.y <= self.r:
            self.vy *= -0.7

        if self.y >= displaySize[1] - self.r:
            self.vy *= -0.7

        return self.x, self.y


ballOne = ball(100,100,50,-100,30,0,0,red)
ballTwo = ball(500,500,-75,0,45,0,0,green)
while 1:
    clock.tick(60)
    screen.fill(blue)
    ballTwo.update()
    ballOne.update()

1 个答案:

答案 0 :(得分:0)

您正在为每个对象调用pygame.display.update(),这会导致闪烁。删除这些调用并在游戏循环中使用pygame.display.flip()

我还建议分离对象的更新和绘图。稍后,您可能希望以与更新对象不同的顺序绘制对象。

典型的游戏循环执行以下操作:

  1. 处理事件
  2. 计算对象的新位置
  3. 绘制下一帧
  4. 展示框架
  5. 在Python中,游戏循环可能如下所示:

    objects = [ballOne, ballTwo]
    while True:
        # 1. handle events
    
        # 2. update objects
        for object in objects:
            object.update()
    
        # 3. draw frame
        screen.fill(blue)
        for object in objects:
            object.draw()
    
        # 4. display frame
        pygame.display.flip()
        clock.tick(60)
    
相关问题