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.



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

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

Instance Attribute Details

#speedObject

The length of the Vector.



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

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.



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

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.



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

def copy; self.clone; end

#pitchObject

The angle along the X/Y axes.



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

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

#pitch=(degrees) ⇒ Object



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

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.



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

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

#x=(value) ⇒ Object



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

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

#yObject

The Y component.



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

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

#y=(value) ⇒ Object



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

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