/lib/chingu/traits/viewport.rb

http://github.com/ippa/chingu · Ruby · 77 lines · 35 code · 9 blank · 33 comment · 4 complexity · 420f3ce7183342b5d5ed3035cddde9b7 MD5 · raw file

  1. #--
  2. #
  3. # Chingu -- OpenGL accelerated 2D game framework for Ruby
  4. # Copyright (C) 2009 ippa / ippa@rubylicio.us
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. #
  20. #++
  21. module Chingu
  22. module Traits
  23. #
  24. # A chingu trait providing velocity and acceleration logic.
  25. # Adds parameters: velocity_x/y, acceleration_x/y and modifies self.x / self.y
  26. # Also keeps previous_x and previous_y which is the x, y before modification.
  27. # Can be useful for example collision detection
  28. #
  29. module Viewport
  30. attr_accessor :viewport
  31. module ClassMethods
  32. def initialize_trait(options = {})
  33. trait_options[:viewport] = {:apply => true}.merge(options)
  34. end
  35. end
  36. def setup_trait(options)
  37. @viewport_options = {:debug => false}.merge(options)
  38. @viewport = Chingu::Viewport.new()
  39. @viewport.x = options[:viewport_x] || 0
  40. @viewport.y = options[:viewport_y] || 0
  41. super
  42. end
  43. def inside_viewport?(object)
  44. puts "Deprecated, use self.viewport.inside?() instead"
  45. object.x >= @viewport.x && object.x <= (@viewport.x + $window.width) &&
  46. object.y >= @viewport.y && object.y <= (@viewport.y + $window.height)
  47. end
  48. # Returns true object is outside the view port
  49. def outside_viewport?(object)
  50. puts "Deprecated, use self.viewport.outside?() instead"
  51. not inside_viewport?(object)
  52. end
  53. # Take care of laggy viewport movements
  54. def update_trait
  55. @viewport.move_towards_target
  56. super
  57. end
  58. #
  59. # Override game states default draw that draws objects relative to the viewport.
  60. # It only draws game objects inside the viewport. (GOSU does no such optimizations)
  61. #
  62. def draw
  63. #self.game_objects.draw_relative(-@viewport.x, -@viewport.y)
  64. @viewport.apply { super }
  65. end
  66. end
  67. end
  68. end