Class: Charming::Projectile

Inherits:
Object
  • Object
show all
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

Classes: Point, Vector

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

Instance Method Summary collapse

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

#accelerationObject (readonly)

Returns the value of attribute acceleration.



35
36
37
# File 'lib/charming/projectile.rb', line 35

def acceleration
  @acceleration
end

#positionObject (readonly)

Returns the value of attribute position.



35
36
37
# File 'lib/charming/projectile.rb', line 35

def position
  @position
end

#velocityObject (readonly)

Returns the value of attribute velocity.



35
36
37
# File 'lib/charming/projectile.rb', line 35

def velocity
  @velocity
end

Instance Method Details

#updateObject

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