【问题标题】:Why does my second called ball in pygame flicker?为什么我在pygame中的第二个被叫球闪烁?
【发布时间】:2017-08-05 11:12:11
【问题描述】:

我用两个实例创建了一个class BallballOneballTwo。当我调用ballTwo.update() 然后ballOne.update() 时,最后调用的球有时会在某些帧上消失,就像它有时会闪烁。有人可以帮忙吗?

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()

【问题讨论】:

标签: python python-2.7 class pygame instance


【解决方案1】:

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

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

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

  1. 处理事件
  2. 计算对象的新位置
  3. 绘制下一帧
  4. 显示框架

在 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-19
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多