我想在Ruby gosu侧滚动游戏中循环背景图像。我有用于翻译背景图像和复制背景图像的计数器@k
和@p
的问题。想不出一个好方法来加上它们。这是使代码更清晰的代码。
require 'gosu'
class GameWindow < Gosu::Window
attr_accessor :x, :y
SHIFT = 700
def initialize
super 640,440
@background = Gosu::Image.new("./images/bg.png")
@player = Gosu::Image.new("./images/000.png")
@x1, @y1 = 0, 0
@player_x, @player_y = 50, 50
@k = 0 #counter
@p = 1 #counter
end
def update
@x1 -= 3
@player_y += 1 if @player_y <= 375
@player_y -= 3 if button_down?(Gosu::KbSpace) and @player_y >= 0
@coordinates = Gosu::Image.from_text(
self, "#{@x1},#{@k}", Gosu.default_font_name, 30)
#here should be the code for @k and @p
end
def draw
@background.draw(@x1 + @k*SHIFT, @y1, 0)
@background.draw(@x1 + @p*SHIFT, @y1, 0)
@player.draw(@player_x, @player_y, 0)
@coordinates.draw(0, 0, 1)
end
def button_down(id)
$window.close if id == Gosu::KbEscape
end
end
window = GameWindow.new
window.show
那么我如何加上计数器@k
和@p
。试过这个
if @x1 > -(SHIFT+5)*@p and @x1 < -SHIFT*@p #705 and 700
@k += 2
end
if @k > 0 and @x1 > -SHIFT*@k - 5 and @x1 < -SHIFT*@k - 3 #1405 and 1403
@p += 2
end
但它只在开始时工作(2-3个图像移位)。 也尝试了这个
if @x1 == -SHIFT*@p
@k += 2
end
它不起作用。
答案 0 :(得分:1)
我假设@x1
和@y1
是最左侧背景原点相对于屏幕的偏移量。您还有@player_x
和@player_y
,表示玩家在屏幕上的位置。您的播放器水平保持在屏幕中央,在跳跃或下降时垂直移动,并且您的背景仅水平滚动。此外,您的窗口大小为640x440,背景图像宽度为700px,高度至少为440px。
你的update
步骤通过修改玩家的屏幕坐标来处理诸如跳跃(但仅限于屏幕顶部)和简单的恒定速度引力之类的事情。它还通过从@x1
减去每帧3个单位来提供恒定的水平滚动,draw
是世界空间中的水平相机坐标。
然后,您的@x1
步骤会拍摄背景图像并绘制其中两个图像,将它们偏移相机偏移@k
加上图像所在的偏移。 然而,这种转变并不重要,因为我们可以相当简单地计算它,而且我们不必操纵额外的记忆状态。
我们不会记住计数器值@p
和@x1
,而是按照图像宽度模数来消除@k
中的多余值,并将其放到我们需要的位置是。 @p
和SHIFT
没用,所以请删除它们。 require 'gosu'
class GameWindow < Gosu::Window
attr_accessor :x, :y # side note - are these used at all?
def initialize
super 640,440
@background = Gosu::Image.new("./images/bg.png")
@player = Gosu::Image.new("./images/000.png")
@x1, @y1 = 0, 0
@player_x, @player_y = 50, 50
end
def update
@x1 -= 3
@player_y += 1 if @player_y <= 375
@player_y -= 3 if button_down?(Gosu::KbSpace) and @player_y >= 0
@coordinates = Gosu::Image.from_text(
self, "#{@x1}", Gosu.default_font_name, 30)
end
def draw
# the important bits!
@local_x = @x1 % -@background.width
@background.draw(@local_x, @y1, 0)
@background.draw(@local_x + @background.width, @y1, 0) if @local_x < (@background.width - self.width)
@player.draw(@player_x, @player_y, 0)
@coordinates.draw(0, 0, 1)
end
def button_down(id) # Side note: Does this work correctly?
$window.close if id == Gosu::KbEscape
end
end
window = GameWindow.new
window.show
也可以删除。
相反,我们需要执行以下操作:
我们的目标看起来像这样:
我们的新代码:
@x1
这样做,它需要install4j version 5.1.6 (build 5598), built on 2013-06-12
和 modulos 它与图像的(负)宽度。这意味着,它给出了两个数的整数除法的余数。当尝试确保在超出任一方向的限制之后整数值“环绕”时,模数非常有用;它有效地将其映射到0(包括)和给定数字(不包括)之间。结果如上图所示。
请记住,此解决方案仅适用于您的情况;垂直滚动需要更多代码,如果窗口比背景图像宽,这将会很快破坏。