Reputation: 43
I am working on this game in pygame and I need to blit some letters on the screen one by one so I created the following code:
def suspicious_print(text, font, font_big, t_w, t_h, fill_colour, rect_colour, text_colour):
pygame.font.init()
font = pygame.font.SysFont(font, font_big)
window_disp.fill(fill_colour)
text_print = ""
for letter in text:
text_print += letter
render = font.render(text_print, 1, text_colour)
render_rect = render.get_rect(center = (t_w, t_h))
pygame.draw.rect(window_disp, rect_colour, render_rect)
window_disp.blit(render, render_rect)
pygame.display.update()
pygame.time.delay(500)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.font.quit()
pygame.quit()
quit()
The problem is the words are moving to the left side every time the letter appears. How can I prevent the words from moving around and have them stay still?
Upvotes: 2
Views: 715
Reputation: 1297
The text is getting centered around (t_w, t_h)
because of render_rect = render.get_rect(center = (t_w, t_h))
. Instead of centering you need to left justify the rectangle and always draw it in the same place.
render_rect = render.get_rect()
render_rect.x = t_w
render_rect.y = t_h
If you want the whole message to be rendered in the center of the screen then you'll need to know 2 things: the size of the final rendered text and the location of the center of the screen. The size of the final box can be found by using the pygame.font.Font.size method on your font. In your case, the following lines should work:
font = pygame.font.SysFont(font, font_big)
box_width, box_height = font.size(text)
Then you can set the position of render_rect
:
render_rect.x = screen_center_x - box_width / 2
render_rect.y = screen_center_y - box_height / 2
I'll leave it up to you to get the center of the screen.
Upvotes: 1