Rendering text in pygame causes lag

徘徊边缘 提交于 2021-02-17 04:57:07

问题


I have write function in my functions module which looks like this

def write(size, writing, color, x,  y):
    font = pygame.font.SysFont("corbel", size)
    text = font.render(writing,  True, color)
    D.blit(text, (x, y))

I imported this to my main module and created a function as follows in the main module

def print_stats():
    write(30, f"Red player's hp {player2.hp}", (200, 50, 50),10, 10)
    write(30, f"Green player's hp {player1.hp}", (50, 200, 50),10, 60)

As long as i dont put print_stats() in the main loop, the game runs perfectly fine, however, as soon i i try to run this function, it heavily drops FPS. I dont see anything in the code that could cause lag, what am i doing wrong? Thanks

Edit: Dont know if this is relevnet but i forgot to mention that i put pygame.init() in all the modules i have imported from as this is my first time using modules and i was unsure.


回答1:


Avoid to create the font object in every frame.
Create a font dependent on the size before the application loop. e.g:

font30 = pygame.font.SysFont("corbel", 30)  
def write(font, writing, color, x, y):
    text = font.render(writing,  True, color)
    D.blit(text, (x, y))
def print_stats():
    write(font30, f"Red player's hp {player2.hp}", (200, 50, 50), 10, 10)
    write(font30; f"Green player's hp {player1.hp}", (50, 200, 50), 10, 60)

That doesn't solve the issue, that the text is rendered in every frame. If it is still lags, then you have to render the text surface once, when player1.hp respectively player2.hp is changed. e.g:

class Player:
    def __init__(self, color, name):
        self.color = color
        self.name = name
        # [...]

    def ChangeHp(self, val):
        self.hp += val
        self.hptext = font30.render(f"{self.name} player's hp {self.hp}", True, self.color)
D.blit(player1.hptext, (10, 60))


来源:https://stackoverflow.com/questions/60469344/rendering-text-in-pygame-causes-lag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!