pyxen.Text
在 Entity 上使用位图字体渲染文本字符串。
Text 实体使用字体图集进行渲染——每个字符都从图集纹理中绘制为一个四边形。
构造函数
Text(
content,
*,
font="_default",
color=None,
align="left"
)
参数
| 参数 | 类型 | 描述 |
|---|---|---|
content | str | 要显示的文本字符串 |
font | str | 字体资源名称(默认:内置字体) |
color | (r, g, b, a) | 着色颜色(默认:白色) |
align | str | 文本对齐方式:"left"、"center" 或 "right" |
content(必填)
要渲染的文本字符串。
Text("Hello World")
font(可选)
要使用的字体资源名称。如果省略,则使用内置默认字体。
Text("Score: 0", font="myfont")
字体资源由一个 .font.json 描述文件和一个 .font.png 图集图像组成。
color(可选)
为渲染的文本着色。
Text("Warning!", color=(1, 0, 0, 1))
默认值:(1.0, 1.0, 1.0, 1.0)(白色,完全不透明)。
align(可选)
控制文本相对于实体位置的水平对齐方式。
Text("Centered", align="center")
| 值 | 描述 |
|---|---|
"left" | 文本从实体位置开始(默认) |
"center" | 文本以实体位置为中心 |
"right" | 文本在实体位置处结束 |
赋值 Text
你可以在生成时赋值:
label = world.spawn(
text=Text("Score: 0"),
x=10, y=10, layer=200
)
或者之后赋值:
label.text = Text("Game Over", color=(1, 0, 0, 1))
运行时更新 Text
通过实体访问 text 组件来更新属性:
label.text.content = "Score: 100"
label.text.color = (1, 1, 0, 1)
label.text.align = "center"
淡出与着色
文本实体的 alpha、r、g 和 b 可以像精灵一样 tween(参见 entity.tween()),弹出的分数无需每帧设置 text.color 就能淡出:
label.tween("alpha", to=0, duration=0.4, delay=0.3) # 稍等片刻后分数淡出
label.tween("b", to=0, duration=0.2) # 白色变为黄色
移除 Text
将 text 设置为 None 即可移除:
label.text = None
在屏幕上还是在世界中
文本实体和精灵一样位于世界中:摄像机移动时它随之移动,摄像机的缩放也会缩放它。要让 HUD(分数、生命数、提示信息)固定在屏幕上,请把文本生成为摄像机的子实体:这样它的 x 和 y 从屏幕中心开始计算,摄像机移动时它在屏幕上保持不动。
cam = world.spawn(camera=Camera())
label = world.spawn(parent=cam, x=-150, y=-80, layer=200, text=Text("Score: 0"))
示例
示例把分数保存在标签的组件中,而不是模块变量中。
from pyxen import *
def start():
cam = world.spawn(camera=Camera())
label = world.spawn(
parent=cam, x=-150, y=-80, layer=200,
text=Text("Score: 0", color=(1, 1, 1, 1))
)
label.score = {"value": 0}
def update():
for label in world.all("score"):
label.score.value += 1
label.text.content = "Score: " + str(label.score.value)