Class: Zyps::Vector
- Inherits:
-
Object
- Object
- Zyps::Vector
- Defined in:
- lib/zyps.rb
Overview
An object or force’s velocity. Has speed and angle components.
Instance Attribute Summary collapse
-
#speed ⇒ Object
The length of the Vector.
Instance Method Summary collapse
-
#+(vector2) ⇒ Object
Add this Vector to vector2, returning a new Vector.
-
#copy ⇒ Object
Make a deep copy.
-
#initialize(speed = 0, pitch = 0) ⇒ Vector
constructor
A new instance of Vector.
-
#pitch ⇒ Object
The angle along the X/Y axes.
- #pitch=(degrees) ⇒ Object
-
#x ⇒ Object
The X component.
- #x=(value) ⇒ Object
-
#y ⇒ Object
The Y component.
- #y=(value) ⇒ Object
Constructor Details
#initialize(speed = 0, pitch = 0) ⇒ Vector
Returns a new instance of Vector.
426 427 428 429 |
# File 'lib/zyps.rb', line 426 def initialize (speed = 0, pitch = 0) self.speed = speed self.pitch = pitch end |
Instance Attribute Details
#speed ⇒ Object
The length of the Vector.
424 425 426 |
# File 'lib/zyps.rb', line 424 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.
456 457 458 459 460 461 462 463 464 465 |
# File 'lib/zyps.rb', line 456 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 |
#copy ⇒ Object
Make a deep copy.
432 |
# File 'lib/zyps.rb', line 432 def copy; self.clone; end |
#pitch ⇒ Object
The angle along the X/Y axes.
435 |
# File 'lib/zyps.rb', line 435 def pitch; Utility.to_degrees(@pitch); end |
#pitch=(degrees) ⇒ Object
436 437 438 439 440 441 |
# File 'lib/zyps.rb', line 436 def pitch=(degrees) #Constrain degrees to 0 to 360. value = degrees % 360 #Store as radians internally. @pitch = Utility.to_radians(value) end |
#x ⇒ Object
The X component.
444 |
# File 'lib/zyps.rb', line 444 def x; @speed.to_f * Math.cos(@pitch); end |
#x=(value) ⇒ Object
445 446 447 |
# File 'lib/zyps.rb', line 445 def x=(value) @speed, @pitch = Math.sqrt(value ** 2 + y ** 2), Math.atan(y / value) end |
#y ⇒ Object
The Y component.
449 |
# File 'lib/zyps.rb', line 449 def y; @speed.to_f * Math.sin(@pitch); end |
#y=(value) ⇒ Object
450 451 452 |
# File 'lib/zyps.rb', line 450 def y=(value) @speed, @pitch = Math.sqrt(x ** 2 + value ** 2), Math.atan(value / x) end |