Class: Rubots::Beam

Inherits:
Object
  • Object
show all
Defined in:
lib/rubots/beam.rb

Constant Summary collapse

HIT_THRESHOLD =

Laser beam is: (x - x0) = tan(angle)(y0 - y) We check for X: x = tan(angle)(y0 - y) + x0 We check for Y y = (x0 - x)/tan(angle) - y0

16

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_x, source_y, angle) ⇒ Beam

Returns a new instance of Beam.



5
6
7
8
9
# File 'lib/rubots/beam.rb', line 5

def initialize(source_x, source_y, angle)
  @source_x = source_x
  @source_y = source_y
  @angle = angle
end

Instance Attribute Details

#angleObject (readonly)

Returns the value of attribute angle.



3
4
5
# File 'lib/rubots/beam.rb', line 3

def angle
  @angle
end

#source_xObject (readonly)

Returns the value of attribute source_x.



3
4
5
# File 'lib/rubots/beam.rb', line 3

def source_x
  @source_x
end

#source_yObject (readonly)

Returns the value of attribute source_y.



3
4
5
# File 'lib/rubots/beam.rb', line 3

def source_y
  @source_y
end

Class Method Details

.from(robot) ⇒ Object



11
12
13
14
# File 'lib/rubots/beam.rb', line 11

def self.from(robot)
  real_angle = (robot.angle + robot.gun_angle) % 360
  new robot.x, robot.y, real_angle
end

Instance Method Details

#check_hit(robot) ⇒ Object



16
17
18
19
20
21
# File 'lib/rubots/beam.rb', line 16

def check_hit(robot)
  if found_hit?(robot)
    robot.destroy
    puts "#{robot.name} hit by laser"
  end
end

#found_hit?(robot) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rubots/beam.rb', line 30

def found_hit?(robot)
  return false if robot.x == @source_x && robot.y == @source_y # Avoid hitting self

  # Check we're pointing to the right quadrant
  return false if robot.x > @source_x && (@angle > 190 && @angle < 350)
  return false if robot.x < @source_x && (@angle < 170 && @angle >  10)
  return false if robot.y > @source_y && (@angle > 280 || @angle <  80)
  return false if robot.y < @source_y && (@angle < 260 && @angle > 100)

  tan_angle = Math.tan(@angle * Math::PI / 180)

  test_x = tan_angle * (@source_y - robot.y) + @source_x
  return true if (test_x - robot.x).abs < HIT_THRESHOLD

  test_y = (@source_x - robot.x)/tan_angle - @source_y
  (test_y - robot.y).abs < HIT_THRESHOLD
end