drawable.rb 1.99 KB
class Drawable

  include Rubygame
  include Sprites::Sprite

  DEFAULTS = {
    image: "placeholder.png",
    zoom: 1.0,
    m: 1000.0,
    p: [0.0, 0.0],
    v: [0.0, 0.0],
    v_limit: 10.0,
    a: 0.0,
    w: 0.0,
    rot: 0.0,
    ctype: :object,
  }

  attr_accessor :game, :size, :shape, :body, :options
  def initialize game, opts = {}
    @game, @options = game, DEFAULTS.merge(opts)
    @surface = Surface.load(File.join(@game.data_dir, "images", options[:image]))
      .rotozoom(0.0, options[:zoom]).to_display_alpha
    @image = @surface
    @body = CP::Body.new(options[:m], 1.0)

    @shape = CP::Shape::Circle.new(@body, @surface.size[0] / 2, CP::Vec2.new(0.0, 0.0))
    @shape.collision_type = options[:ctype]

    @body.p = CP::Vec2.new(*options[:p])
    @body.v = CP::Vec2.new(*options[:v])
    @body.v_limit = options[:v_limit]
    @body.a = options[:a]
    @body.w = options[:w]

    game.space.add_body(@body)
    game.space.add_shape(@shape)

    @alive = true
  end

  def pos; @body.p.to_a; end; alias_method :p, :pos
  def vel; @body.v.to_a; end; alias_method :v, :vel
  def rot; @body.a; end; alias_method :a, :rot

  def rect
    Rect.new(@body.p.to_a, @surface.size)
  end

  def screen
    @game.screen
  end

  def size
    @surface.size
  end

  def draw screen
    s = @surface.rotozoom(@body.a, 1.0).to_display_alpha
    s.blit(screen, pos.sub(s.size[0] / 2))
    screen.draw_circle(pos, @shape.r, :red)  if @game.options[:debug]
  end

  def show
    @game.objects << self
    @visible = true
  end

  def hide
    @game.objects.delete(self)
    @visible = false
  end

  def collides? other
    return false  unless @visible
    ((pos[0]..pos[0]+size[0]).to_a & (other.pos[0]..other.pos[0]+other.size[0]).to_a).any? &&
      ((pos[1]..pos[1]+size[1]).to_a & (other.pos[1]..other.pos[1]+other.size[1]).to_a).any?
  end

  def debug
    @font ||= @game.font("FreeSans", 10)
    @debug = @font.render("[ #{self.class}: v: #{@body.v}, a: #{@body.a}, m: #{@body.m} ]", false, :white).to_display
  end

end