def initialize
super 200, 135, false
self.caption = "Gosu Cycle Example"
@shape_x = 0
# Create and load an image to display
@background_image = Gosu::Image.new("media/earth.png") #this is causing the error
# Create and load a font for drawing text on the screen
@font = Gosu::Font.new(20)
@cycle = 0
puts "0. In initialize\n"
end
I keep getting an error with the background image initialization. It keeps giving an error where it can't find the file specified. The image is in a folder called 'media' which is in the folder for the program.
I had a similar issue with the 'require' but fixed it with 'require_relative'. I cannot find such a solution for this issue.
Gosu does support relative paths, but they're relative to the working directory where you're invoking the game from, not relative to the source file. This might be what's tripping you up here!
For example, for the following directory structure:
game
|--- src
| '--- main.rb
'--- res
'--- image.png
If you had the game
folder as your working directory and ran ruby src/main.rb
, then Gosu would be able to access the image relatively as res/image.png
.
This means you'd have to execute your game from a particular working directory every time, but obviously that's not ideal.
Instead of using these awkward relative paths, it might be helpful to use __dir__
along with File.expand_path
to grab the absolute path to your directory which your script is running in, and concatenate onto that path, like this:
# Running from src/main.rb
File.expand_path(File.join(__dir__, "../res/image.png"))
# => "/wherever/game/res/image.png"
This is better than hardcoding an absolute path because your game would still work on somebody else's computer.