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

832 Views Asked by At

I have a text object in ruby 2D showing score. How do I update the text?

I have this so far

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

Instead of replacing it, it is creating a new text object on top of it. How could you replace it instead of adding it on?

2

There are 2 best solutions below

0
arcadeblast77 On BEST ANSWER

Based on docs it seems like you need to instantiate the Text object outside of the update loop. This will draw it to the screen "forever" until you call the remove method.

In your current code you are just instantiating a new object every time, and Ruby 2D is secretly keeping it around even though you don't have it assigned to a variable.

Unlike some other 2D libraries like Gosu, Ruby 2D does not stop drawing something until you explicitly tell it to.

Try

@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

0
Nifriz On

here a simple example how to use the Text class in ruby2d

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