Module: Chingu::Traits::BoundingBox

Defined in:
lib/chingu/traits/bounding_box.rb

Overview

Providing a bounding_box-method which generates a AABB on the fly from: x, y, factor_x, factor_y and rotation_center

Defined Under Namespace

Modules: ClassMethods

Constant Summary

CENTER_TO_FACTOR =
{ 0 => -1, 0.5 => 0, 1 => 1 }

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#collidableObject

Returns the value of attribute collidable



30
31
32
# File 'lib/chingu/traits/bounding_box.rb', line 30

def collidable
  @collidable
end

Instance Method Details

#bounding_boxObject Also known as: bb

Returns an instance of class Rect



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/chingu/traits/bounding_box.rb', line 51

def bounding_box        
  if @cached_bounding_box
    @cached_bounding_box.x = self.x + @_x_diff
    @cached_bounding_box.y = self.y + @_y_diff
    
    return @cached_bounding_box
  end
  
  width, height = self.width, self.height
  
  if scale = trait_options[:bounding_box][:scale]
    width_scale, height_scale = scale.is_a?(Array) ? [scale[0],scale[1]] : [scale,scale]
    width  *= width_scale
    height *= height_scale
  end
          
  x = self.x - width * self.center_x
  y = self.y - height * self.center_y
  x += width * CENTER_TO_FACTOR[self.center_x]   if self.factor_x < 0
  y += height * CENTER_TO_FACTOR[self.center_y]  if self.factor_y < 0

  return Rect.new(x, y, width, height)
end

#cache_bounding_boxObject



76
77
78
79
80
81
# File 'lib/chingu/traits/bounding_box.rb', line 76

def cache_bounding_box
  @cached_bounding_box = nil
  @cached_bounding_box = self.bounding_box
  @_x_diff = @cached_bounding_box.x - self.x
  @_y_diff = @cached_bounding_box.y - self.y
end

#collision_at?(x, y) ⇒ Boolean



44
45
46
# File 'lib/chingu/traits/bounding_box.rb', line 44

def collision_at?(x, y)
  bounding_box.collide_point?(x,y)
end

#draw_debugObject

Visualises the bounding box as a red rectangle.



96
97
98
# File 'lib/chingu/traits/bounding_box.rb', line 96

def draw_debug
  $window.draw_rect(self.bounding_box, Chingu::DEBUG_COLOR, Chingu::DEBUG_ZORDER)
end

#draw_traitObject

def update_trait

cache_bounding_box  if trait_options[:bounding_box][:cache] && !@cached_bounding_box
super

end



88
89
90
91
# File 'lib/chingu/traits/bounding_box.rb', line 88

def draw_trait      
  draw_debug if trait_options[:bounding_box][:debug]
  super
end

#setup_trait(options) ⇒ Object



38
39
40
41
42
# File 'lib/chingu/traits/bounding_box.rb', line 38

def setup_trait(options)
  @cached_bounding_box = nil
  @collidable = true
  super
end