python - Pygame 在旧文本上渲染文本
问题描述
我有以下函数可以绘制到 pygame 窗口:
base.draw(win, rocket.in_space)
win.blit(rocket_img, (120, 150))
if rocket.in_space:
velocity_label = STAT_FONT.render(f"Velocity: {round(rocket.velocity, 3)} km/s", True, (255, 255, 255))
acceleration_label = STAT_FONT.render(f"Acceleration: {round(rocket.acceleration, 3)} km/s^2", True, (255, 255, 255))
altitude_label = STAT_FONT.render(f"Altitude: {round(rocket.altitude, 3)} km", True, (255, 255, 255))
fuel_label = STAT_FONT.render(f"Fuel: {round(rocket.fuel, 2)} kg", True, (255, 255, 255))
time_label = STAT_FONT.render(f"Time: {round(rocket.time_passed, 2)} s", True, (255, 255, 255))
else:
velocity_label = STAT_FONT.render(f"Velocity: {round(rocket.velocity, 3)} km/s", True, (0, 0, 0))
acceleration_label = STAT_FONT.render(f"Acceleration: {round(rocket.acceleration, 3)} km/s^2", True, (0, 0, 0))
altitude_label = STAT_FONT.render(f"Altitude: {round(rocket.altitude, 3)} km", True, (0, 0, 0))
fuel_label = STAT_FONT.render(f"Fuel: {round(rocket.fuel, 2)} kg", True, (0, 0, 0))
time_label = STAT_FONT.render(f"Time: {round(rocket.time_passed, 2)} s", True, (0, 0, 0))
win.blit(velocity_label, (0, 0))
win.blit(acceleration_label, (0, 50))
win.blit(altitude_label, (0, 100))
win.blit(fuel_label, (0, 150))
win.blit(time_label, (0, 200))
pygame.display.update()
这段代码使背景移动:
class Base:
VEL = 5
HEIGHT = bg_img.get_height()
IMG = bg_img
space = space_img
def __init__(self, x):
self.x = x
self.y1 = 0
self.y2 = self.HEIGHT
def move(self, vel):
self.VEL = vel
self.y1 -= self.VEL
self.y2 -= self.VEL
if self.y1 + self.HEIGHT < 0:
self.y1 = self.y2 + self.HEIGHT
if self.y2 + self.HEIGHT < 0:
self.y2 = self.y1 + self.HEIGHT
def draw(self, win, in_space):
if in_space:
win.blit(self.space, (self.x, self.y2))
win.blit(self.space, (self.x, self.y1))
else:
win.blit(self.IMG, (self.x, self.y2))
win.blit(self.IMG, (self.x, self.y1))
但是,当背景开始加速时,文本开始呈现在自身之上。我不确定为什么会这样。任何帮助是极大的赞赏。
编辑: 基地移动的速度随着时间的推移而增加
这是屏幕冻结时的样子。
解决方案
问题是计算背景的 y 坐标。self.VEL
如果大于,算法就会崩溃HEIGHT
。使用模 ( %
) 运算符计算 y 坐标:
class Base:
VEL = 5
HEIGHT = bg_img.get_height()
IMG = bg_img
space = space_img
def __init__(self, x):
self.x = x
self.y = 0
def move(self, vel):
self.VEL = vel
self.y = (self.y - self.VEL) % self.HEIGHT
def draw(self, win, in_space):
if in_space:
win.blit(self.space, (self.x, self.y - self.HEIGHT))
win.blit(self.space, (self.x, self.y))
else:
win.blit(self.IMG, (self.x, self.y - self.HEIGHT))
win.blit(self.IMG, (self.x, self.y))
推荐阅读
- c# - 试图让我的 C# WEB API 2 返回一个对象,但得到错误 500
- react-native - 触摸图标时,React-Native onPress 不起作用
- sql - 创建应该引发应用程序错误的触发器时出错
- android-studio - 如何在 Android Studio 中检查代码指标(代码行、死代码行、圈复杂度等)
- d3.js - D3 wForceSimulation 的多个实例
- javascript - AFrame / Three.js:加载复杂的 .obj 文件时,为什么内存中有这么多(JS)字符串?
- angularjs - ng 在具有动态键的对象中重复
- ruby-on-rails - Rails / Rspec:让匿名控制器属于某个类
- javascript - Javascript中的增加和减少值
- vb.net - 从 RichTextBox 的列表中删除描述