0

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

tadman
  • 208,517
  • 23
  • 234
  • 262
  • What version of ruby? What platform? What version of ruby2d? Please include the necessary information to replicate your environment. – anothermh Apr 10 '19 at 16:03
  • ah sorry, i'm using windows 10, ruby version 2.5.1p57 64 bit and ruby2D version 0.9.0 – carl schimdt Apr 10 '19 at 16:41
  • This isn't enough code to reproduce the problem. What's the most minimal, complete program that still crashes? – tadman Apr 10 '19 at 17:07
  • @tadman apparently it is not very far from it though [Key Event Example](https://github.com/ruby2d/examples/blob/master/keyevent-example/keyevent-example.rb). Also not that I have any idea how ruby 2d works but wouldn't a higher y coordinate be up? If so then this code would seemingly make you drop 25 (y units) and then raise back up to where you were more like a dive than a jump. – engineersmnky Apr 10 '19 at 17:26
  • @engineersmnky There's presumably some other surrounding code to frame this `on`. – tadman Apr 10 '19 at 17:43
  • true we lack a definition for `player` and `player#y` – engineersmnky Apr 10 '19 at 17:46
  • https://pastebin.com/73U2jqxS – carl schimdt Apr 11 '19 at 06:07

1 Answers1

0

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
Nifriz
  • 1,033
  • 1
  • 10
  • 21