Class: Charming::Projectile
- Inherits:
-
Object
- Object
- Charming::Projectile
- Defined in:
- lib/charming/projectile.rb
Overview
Projectile is simple physics motion for games: a position advanced by a velocity, and a velocity advanced by an acceleration (typically gravity), one fixed time step per frame (semi-implicit Euler, matching charmbracelet/harmonica's projectile):
ball = Charming::Projectile.new(
delta_time: Charming.fps(60),
position: Charming::Projectile::Point.new(x: 0.0, y: 0.0),
velocity: Charming::Projectile::Vector.new(x: 20.0, y: 0.0),
acceleration: Charming::Projectile::TERMINAL_GRAVITY
)
position = ball.update # each frame
Defined Under Namespace
Constant Summary collapse
- GRAVITY =
Gravity for a coordinate plane whose origin is bottom-left (y grows upward).
Vector.new(x: 0.0, y: -9.81)
- TERMINAL_GRAVITY =
Gravity for terminal coordinates, whose origin is top-left (y grows downward).
Vector.new(x: 0.0, y: 9.81)
Instance Attribute Summary collapse
-
#acceleration ⇒ Object
readonly
Returns the value of attribute acceleration.
-
#position ⇒ Object
readonly
Returns the value of attribute position.
-
#velocity ⇒ Object
readonly
Returns the value of attribute velocity.
Instance Method Summary collapse
-
#initialize(delta_time:, position:, velocity: Vector.new(x: 0.0, y: 0.0), acceleration: Vector.new(x: 0.0, y: 0.0)) ⇒ Projectile
constructor
A new instance of Projectile.
-
#update ⇒ Object
Advances one frame and returns the new position.
Constructor Details
#initialize(delta_time:, position:, velocity: Vector.new(x: 0.0, y: 0.0), acceleration: Vector.new(x: 0.0, y: 0.0)) ⇒ Projectile
Returns a new instance of Projectile.
37 38 39 40 41 42 |
# File 'lib/charming/projectile.rb', line 37 def initialize(delta_time:, position:, velocity: Vector.new(x: 0.0, y: 0.0), acceleration: Vector.new(x: 0.0, y: 0.0)) @delta_time = delta_time @position = position @velocity = velocity @acceleration = acceleration end |
Instance Attribute Details
#acceleration ⇒ Object (readonly)
Returns the value of attribute acceleration.
35 36 37 |
# File 'lib/charming/projectile.rb', line 35 def acceleration @acceleration end |
#position ⇒ Object (readonly)
Returns the value of attribute position.
35 36 37 |
# File 'lib/charming/projectile.rb', line 35 def position @position end |
#velocity ⇒ Object (readonly)
Returns the value of attribute velocity.
35 36 37 |
# File 'lib/charming/projectile.rb', line 35 def velocity @velocity end |
Instance Method Details
#update ⇒ Object
Advances one frame and returns the new position. Position moves by the current velocity before the velocity accelerates — keep this order.
46 47 48 49 50 |
# File 'lib/charming/projectile.rb', line 46 def update @position = shift(position, velocity) @velocity = shift(velocity, acceleration) position end |