Chingu示例看起来像这样:
require 'rubygems'
require 'chingu'
class Game < Chingu::Window
def initialize
super
@player = Player.new
end
end
class Player < Chingu::GameObject
def initialize(options = {})
super(options.merge(:image => Gosu::Image["player.png"])
end
end
Game.new.show
如果我想用线而不是图像绘制Player对象,我该怎么做呢?
以下代码看似直观,但我无法让它工作!
class Player < Chingu::BasicGameObject
def initialize(options = {})
super
@radius = options[:radius]
@c = Gosu::Color.new(0xffff0000)
end
def draw
$window.draw_rect([@x-1,@y+1,@x+1,@y+1,@x+1,@y-1,@x+1,@y+1],@c,1)
end
end
我做错了吗?
答案 0 :(得分:5)
让我们弄清楚。
我认为这些是您实际代码的不完整摘要, 因为显示的代码调用draw_rect,@ x和@y设置为nil, 抛出'未定义的方法' - '为nil:nilClass'异常,因为 你不能从零中减去任何东西。)
我怀疑你看到一个没有画出的空白窗口, 因为写完后,你的Player.draw永远不会被调用。
为什么呢?因为Chingu为所有人提供自动绘图和更新 它的GameObjects,但只有你使用GameObject.create而不是 GameObject.new。
(http://rdoc.info/projects/ippa/chingu)
Chingu ::游戏物体
在游戏中使用此功能 对象。玩家,敌人,玩家 子弹,通电,战利品 四处走动。它非常可重复使用 不包含任何游戏逻辑 (随你(由你决定!)。只有东西放 它在屏幕上以某种方式。如果你这样做 GameObject.create()而不是new() Chingu将继续保存对象 “game_object” - 自动列表 更新/平局。
Chingu :: BasicGameObject
新的()vs create()行为 GameObject来自BasicGameObject。
所以我们需要解决这个问题。然而...
现在每个帧都正确调用了Player.draw 通过Chingu,我们发现了一个新问题: 调用draw_rect不起作用!这就是Ruby告诉我的:
draw_rect': undefined method
x'中的[99,101,101,101,101,99,101,101]中的:数组(NoMethodError)
嗯......我可以看到传递给draw_rect方法的内容, 我想知道它会收到什么?我们来看看代码。
(http://github.com/ippa/chingu/blob/master/lib/chingu/helpers/gfx.rb)
# Draws an unfilled rect in given color
#
def draw_rect(rect, color, zorder)
$window.draw_line(rect.x, rect.y, color, rect.right, rect.y, color, zorder)
$window.draw_line(rect.right, rect.y, color, rect.right, rect.bottom, color, zorder)
$window.draw_line(rect.right, rect.bottom, color, rect.x, rect.bottom, color, zorder)
$window.draw_line(rect.x, rect.bottom, color, rect.x, rect.y, color, zorder)
end
啊,现在有道理了。 draw_rect期望传递一个Rectangle对象,而不是
一堆坐标。这是:
(http://rdoc.info/projects/ippa/chingu)
Chingu::Rect
Constructor Details
- (Rect) initialize(*argv)
Create a new Rect, attempting to extract its own information from the
given arguments.
The arguments must fall into one of these cases:
- 4 integers +(x, y, w, h)+.
- 1 Rect or Array containing 4 integers +([x, y, w, h])+.
- 2 Arrays containing 2 integers each +([x,y], [w,h])+.
- 1 object with a +rect+ attribute which is a valid Rect object.
All rect core attributes (x,y,w,h) must be integers.
所以我们首先需要创建一个Rect对象,然后调用 draw_rect,将Rect作为第一个参数。
好的,让我们这样做。这是工作代码 -
require 'rubygems'
require 'chingu'
class Game < Chingu::Window
def initialize
super
puts "initializing player..."
@player = Player.create
end
end
class Player < Chingu::BasicGameObject
def initialize(options = {})
super
@x = 100
@y = 100
@rect = Chingu::Rect.new(@x, @y, 10, 10)
@c = Gosu::Color.new(0xffff0000)
end
def draw
puts "inside draw"
puts @x, @y
$window.draw_rect(@rect, @c, 1)
end
end
Game.new.show
现在运行它会显示一个100,100的小红色矩形。
希望有所帮助。
C〜