2007-01-10
[MyGame]MyGame で実装する「THE APPLE CATCHER」(3)

本家のサンプルでは横歩きのアニメパタンが使われていないようだったけど、画像の中には4方向のアニメパタンが描かれていたので使ってみた。
MyGame でのアニメーションの扱いについて解説。 次のサンプルは Player クラスを作成し、方向キーでキャラクターを歩かせるサンプル。キャラクターが移動するとともにアニメーションもその方向に変わる。
#!ruby -Ks
require 'mygame/boot'
# プレイヤークラス
class Player
def initialize
@image = TransparentImage.new("images/player.png", :x => 0, :y => 40)
# 描画サイズを設定
@image.w = 64
@image.h = 64
# アニメーションパタンをセット
animations = {
:down => [12, [ 0, 1, 2, 3]], # ↓ 向き
:right => [12, [ 4, 5, 6, 7]], # → 向き
:up => [12, [ 8, 9,10,11]], # ↑ 向き
:left => [12, [12,13,14,15]], # ← 向き
}
@image.add_animation animations
# アニメーション開始
@image.start_animation :down
# 画面中央に配置
@image.x = (screen.w - @image.w) / 2
@image.y = (screen.h - @image.h) / 2
end
def move
if key_pressed?(Key::RIGHT)
@image.x += 4
@image.start_animation :right
end
if key_pressed?(Key::LEFT)
@image.x -= 4
@image.start_animation :left
end
if key_pressed?(Key::DOWN)
@image.y += 4
@image.start_animation :down
end
if key_pressed?(Key::UP)
@image.y -= 4
@image.start_animation :up
end
end
def update
move
@image.update
end
def render
@image.render
end
end
player = Player.new
main_loop do
player.update
player.render
end
アニメーションパタンはあらかじめひとつの画像の中にならべて描いておく。 アニメーション名を示すシンボルとオフセット値を列挙してアニメーションを定義する。
animations = { # パターンを列挙した Hash オブジェクト
:label => [time, [*patten]] following,
・
・
・
}
image.add_animation animations
following には次のアニメーション名のシンボルを指定することができる。 デフォルトでは繰り返しループ。
追記(2007年3月31日):最新の MyGame に合わせてサンプルと解説を修正。