Class: Zyps::Vector

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

Overview

An object or force’s velocity. Has speed and angle components.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(speed = 0, pitch = 0) ⇒ Vector

Returns a new instance of Vector.



464
465
466
467
# File 'lib/zyps.rb', line 464

def initialize (speed = 0, pitch = 0)
  self.speed = speed
  self.pitch = pitch
end

Instance Attribute Details

#speedObject

The length of the Vector.



462
463
464
# File 'lib/zyps.rb', line 462

def speed
  @speed
end

Instance Method Details

#+(vector2) ⇒ Object

Add this Vector to vector2, returning a new Vector. This operation is useful when calculating the effect of wind or thrust on an object’s current heading.



494
495
496
497
498
499
500
501
502
503
# File 'lib/zyps.rb', line 494

def +(vector2)
  #Get the x and y components of the new vector.
  new_x = (self.x + vector2.x)
  new_y = (self.y + vector2.y)
  new_length_squared = new_x ** 2 + new_y ** 2
  new_length = (new_length_squared == 0 ? 0 : Math.sqrt(new_length_squared))
  new_angle = (new_x == 0 ? 0 : Utility.to_degrees(Math.atan2(new_y, new_x)))
  #Calculate speed and angle of new vector with components.
  Vector.new(new_length, new_angle)
end

#copyObject

Make a deep copy.



470
# File 'lib/zyps.rb', line 470

def copy; self.clone; end

#pitchObject

The angle along the X/Y axes.



473
# File 'lib/zyps.rb', line 473

def pitch; Utility.to_degrees(@pitch); end

#pitch=(degrees) ⇒ Object



474
475
476
477
478
479
# File 'lib/zyps.rb', line 474

def pitch=(degrees)
  #Constrain degrees to 0 to 360.
  value = degrees % 360
  #Store as radians internally.
  @pitch = Utility.to_radians(value)
end

#xObject

The X component.



482
# File 'lib/zyps.rb', line 482

def x; @speed.to_f * Math.cos(@pitch); end

#x=(value) ⇒ Object



483
484
485
# File 'lib/zyps.rb', line 483

def x=(value)
  @speed, @pitch = Math.sqrt(value ** 2 + y ** 2), Math.atan(y / value)
end

#yObject

The Y component.



487
# File 'lib/zyps.rb', line 487

def y; @speed.to_f * Math.sin(@pitch); end

#y=(value) ⇒ Object



488
489
490
# File 'lib/zyps.rb', line 488

def y=(value)
  @speed, @pitch = Math.sqrt(x ** 2 + value ** 2), Math.atan(value / x)
end