/examples/example11_animation.rb

http://github.com/ippa/chingu · Ruby · 83 lines · 50 code · 16 blank · 17 comment · 5 complexity · 6a3a6d85e318ec0ec763e8f3ef1069e5 MD5 · raw file

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