Ruby interpretor crashes on :key_down

125 Views Asked by At

i'm new to ruby and programming in general and i'm using a gem called ruby2D. Im trying to get a cube to jump, but when i press my jump key, my interpretor just crashes without any saying any errors

I've had problems actually identifying the problem, but i've tried with while instead of until and that didn't seem to work either

on :key_down do |jump|
 if jump.key == 'j'
  if player.y == 520
   gravity = -15
   player.y = 510
   until player.y == 520
    player.y += gravity
    gravity += 1
   end
  end
 end
end 

i would want my cube to jump, and fall down again, but i just get crashes

1

There are 1 best solutions below

0
Nifriz On

In Ruby2D you must use tick to do animation.

The window also manages the update loop, one of the few infinite loops in programming you’ll encounter that isn’t a mistake. Every window has a heartbeat, a loop that runs 60 times per second, or as close to it as the computer’s performance will allow. Using the update method, we can enter this loop and make the window come to life!

Try something like this:

require 'ruby2d'

set title: 'squares'
set background: 'blue'
set width: 1280
set height: 720
set borderless: true

on_air = false 
tick = 0


ground = Rectangle.new(
 x: 0, y: 620,
 width: 1280, height: 100,
 color: 'green'
)

player = Square.new(
 x: 100, y: 520,
 size: 100,
 color: ['red', 'purple', 'fuchsia', 'maroon']
)

on :key_down do |jump|
 if jump.key == 'j'
  player.y -= 50
  on_air = true
 end
end

update do
  if on_air
   if tick % 1 == 0
     player.y += 5
     if (player.y + player.size) == ground.y
      on_air = false
     end     
   end
  end

  tick += 1
end

show