PageRenderTime 28ms CodeModel.GetById 21ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/example11_animation.rb

http://github.com/ippa/chingu
Ruby | 83 lines | 50 code | 16 blank | 17 comment | 5 complexity | 6a3a6d85e318ec0ec763e8f3ef1069e5 MD5 | raw file
Possible License(s): LGPL-2.1
 1#!/usr/bin/env ruby
 2require 'rubygems' rescue nil
 3$LOAD_PATH.unshift File.join(File.expand_path(__FILE__), "..", "..", "lib")
 4require 'chingu'
 5include Gosu
 6include Chingu
 7
 8#
 9# Animation / retrofy example
10#
11class Game < Chingu::Window  
12  def initialize
13    super    
14    self.factor = 6
15    self.input = { :escape => :exit }
16		self.caption = "Chingu::Animation / retrofy example. Move with arrows!"
17    retrofy
18    Droid.create(:x => $window.width/2, :y => $window.height/2)
19  end
20end
21
22class Droid < Chingu::GameObject
23  traits :timer
24  
25  def initialize(options = {})
26    super
27    
28    #
29    # This shows up the shorten versio of input-maps, where each key calls a method of the very same name.
30    # Use this by giving an array of symbols to self.input
31    #
32    self.input = [:holding_left, :holding_right, :holding_up, :holding_down]
33    
34    # Load the full animation from tile-file media/droid.bmp
35    @animation = Chingu::Animation.new(:file => "droid_11x15.bmp")
36    @animation.frame_names = { :scan => 0..5, :up => 6..7, :down => 8..9, :left => 10..11, :right => 12..13 }
37    
38    # Start out by animation frames 0-5 (contained by @animation[:scan])
39    @frame_name = :scan
40    
41    @last_x, @last_y = @x, @y
42    update
43  end
44    
45  def holding_left
46    @x -= 2
47    @frame_name = :left
48  end
49
50  def holding_right
51    @x += 2
52    @frame_name = :right
53  end
54  
55  def holding_up
56    @y -= 2
57    @frame_name = :up
58  end
59
60  def holding_down
61    @y += 2
62    @frame_name = :down
63  end
64
65  # We don't need to call super() in update().
66  # By default GameObject#update is empty since it doesn't contain any gamelogic to speak of.
67  def update
68    
69    # Move the animation forward by fetching the next frame and putting it into @image
70    # @image is drawn by default by GameObject#draw
71    @image = @animation[@frame_name].next
72    
73    #
74    # If droid stands still, use the scanning animation
75    #
76    @frame_name = :scan if @x == @last_x && @y == @last_y
77    
78    @x, @y = @last_x, @last_y if outside_window?  # return to previous coordinates if outside window
79    @last_x, @last_y = @x, @y                     # save current coordinates for possible use next time
80  end
81end
82
83Game.new.show