Ruby Gosu 找不到背景图片
Ruby Gosu not able to find the background image
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
我总是收到背景图片初始化错误。它一直在找不到指定文件的地方出错。该图像位于程序文件夹中名为 'media' 的文件夹中。
Here is the error
我对 'require' 也有类似的问题,但用 'require_relative' 修复了它。我找不到解决此问题的方法。
你必须给出绝对路径:
/Users/{name}/.../media/earth.png
上面的例子是 Mac.
Gosu 确实支持相对路径,但它们相对于您从中调用游戏的工作目录,而不是相对于源文件。这可能就是让你在这里绊倒的原因!
例如,对于以下目录结构:
game
|--- src
| '--- main.rb
'--- res
'--- image.png
如果您将 game
文件夹作为您的工作目录并且 运行 ruby src/main.rb
,那么 Gosu 将能够以 res/image.png
.[= 的形式访问图像。 17=]
这意味着您每次都必须从特定的工作目录执行游戏,但显然这并不理想。
与其使用这些笨拙的相对路径,不如使用 __dir__
和 File.expand_path
来获取脚本所在目录的绝对路径 运行,并连接到该路径,如下所示:
# Running from src/main.rb
File.expand_path(File.join(__dir__, "../res/image.png"))
# => "/wherever/game/res/image.png"
这比硬编码绝对路径要好,因为您的游戏仍然可以在其他人的计算机上运行。
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
我总是收到背景图片初始化错误。它一直在找不到指定文件的地方出错。该图像位于程序文件夹中名为 'media' 的文件夹中。
Here is the error
我对 'require' 也有类似的问题,但用 'require_relative' 修复了它。我找不到解决此问题的方法。
你必须给出绝对路径:
/Users/{name}/.../media/earth.png
上面的例子是 Mac.
Gosu 确实支持相对路径,但它们相对于您从中调用游戏的工作目录,而不是相对于源文件。这可能就是让你在这里绊倒的原因!
例如,对于以下目录结构:
game
|--- src
| '--- main.rb
'--- res
'--- image.png
如果您将 game
文件夹作为您的工作目录并且 运行 ruby src/main.rb
,那么 Gosu 将能够以 res/image.png
.[= 的形式访问图像。 17=]
这意味着您每次都必须从特定的工作目录执行游戏,但显然这并不理想。
与其使用这些笨拙的相对路径,不如使用 __dir__
和 File.expand_path
来获取脚本所在目录的绝对路径 运行,并连接到该路径,如下所示:
# Running from src/main.rb
File.expand_path(File.join(__dir__, "../res/image.png"))
# => "/wherever/game/res/image.png"
这比硬编码绝对路径要好,因为您的游戏仍然可以在其他人的计算机上运行。