pull/1/head
E. Almqvist 3 years ago
parent 4b79205e53
commit ede0ee7f5e
  1. 19
      app.rb
  2. 40
      physobj.rb

@ -3,21 +3,26 @@ require "gosu"
load "physobj.rb"
class Window < Gosu::Window
attr_accessor :caption, :physobjs
attr_accessor :caption, :physobjs, :planets
attr_reader :width, :height
def initialize(title, width, height, physobjs = [])
def initialize(title, width, height, physobjs = [], planets = [])
super width, height
@width, @height = width, height
self.caption = "#{title}| #{width}x#{height}"
@physobjs = physobjs
@planets = planets
end
def update
@physobjs.each do |obj|
obj.physics
end
@planets.each do |planet|
planet.orbit(@physobjs)
end
end
def draw
@ -26,19 +31,23 @@ class Window < Gosu::Window
obj.draw_vector(obj.vel, 10)
obj.draw_vector(obj.accel, 500, 0xff_aaffaa)
end
@planets.each do |planet|
planet.render
end
end
end
window = Window.new("Physics!", 1600, 900)
planet = PhysCube.new("Earth", window, 16, 16, 0xff_aaffaa)
planet = Planet.new("Earth", window, 0xff_aaffaa)
planet.pos = Vector[800, 450]
cube = PhysCube.new("Cube", window, 8, 8)
cube.accel = Vector[0, 0.1]
cube.vel = Vector[10, 0]
planet.orbit([cube])
window.physobjs << planet
window.planets << planet
window.physobjs << cube
window.show

@ -1,5 +1,6 @@
require "matrix"
class PhysObj
attr_accessor :world, :pos, :vel, :accel, :x, :y
attr_reader :name
@ -48,15 +49,14 @@ class PhysCube < PhysObj
x_max = world.width - self.width
y_max = world.height - self.height
if( x > x_max ) then
self.pos[0] = x_max
self.vel[0] = 0
end
if( y > y_max ) then
self.pos[1] = y_max
self.vel[1] = 0
end
# if( x > x_max ) then
# self.pos[0] = x_max
# self.vel[0] = 0
# end
# if( y > y_max ) then
# self.pos[1] = y_max
# self.vel[1] = 0
# end
end
def draw_vector(vec, scale=2, color=0xaf_ffaaaa)
@ -79,3 +79,25 @@ class PhysCube < PhysObj
end
end
class Planet < PhysCube
attr_reader :gravity
def initialize(name, world, color, gravity=0.1)
super name, world, gravity*400, gravity*400, color
@gravity = gravity
end
private def calculate_gravity_vector(obj)
dir_vec = self.pos - obj.pos
return (self.gravity * dir_vec)/dir_vec.magnitude
end
def orbit(physobjs)
physobjs.each do |obj|
grav_vec = self.calculate_gravity_vector(obj)
obj.accel = grav_vec
end
end
end

Loading…
Cancel
Save