如何更新和更改 ruby 2D 中的对象?

How do you update and change an object in ruby 2D?

我有一个 ruby 二维显示乐谱的文本对象。如何更新文本?

目前我有这个

    update do
      text = Text.new("Score: #{@score}")
    end

它不是替换它,而是在它之上创建一个新的文本对象。你怎么能替换它而不是添加它?

基于 docs 看来您需要在 update 循环之外实例化 Text 对象。这会将它绘制到屏幕 "forever" 直到您调用 remove 方法。

在您当前的代码中,您每次都只是实例化一个新对象,并且 Ruby2D 会秘密地保留它,即使您没有将它分配给变量。

与 Gosu 等其他一些 2D 库不同,Ruby 2D 不会停止绘制某些东西,除非您明确告诉它。

尝试

@text = Text.new("Score: #{@score}")
update do
    ...
    @text.remove # At a time you want to stop displaying that text.
    ...
end

Adding and removing objects in Ruby 2D

这里有一个简单的例子如何在ruby2d

中使用Textclass
require 'ruby2d'

sector = 3
txt = Text.new(
  sector.to_s,
  x: 10, y: 10,
  size: 20,
  color: 'white',
  z: 10
)

on :key_down do |event|
  case event.key
  when 'a'
    sector += 1
    txt.text = sector.to_s
  when 's'
    sector -= 1
    txt.text = sector.to_s
  end
end

show