Sha256: 96bf9fb37a254bf8c223768632ed5f1afce7ba6d2d9bb3a12ae3121ba324689f

Contents?: true

Size: 1.46 KB

Versions: 4

Compression:

Stored size: 1.46 KB

Contents

require 'ruby-processing'

class Planet

  # Each planet object keeps track of its own angle of rotation.
  # @theta        Rotation around sun
  # @diameter     Size of planet
  # @distance     Distance from sun
  # @orbit_speed  Orbit speed
  def initialize(distance, diameter)
    @distance = distance
    @diameter = diameter
    @theta = 0
    @orbit_speed = rand * 0.02 + 0.01
  end

  def update
    # Increment the angle to rotate
    @theta += @orbit_speed
  end

  def display
    # Before rotation and translation, the state of the matrix is saved with push_matrix.
    $app.push_matrix 
    # Rotate orbit
    $app.rotate @theta 
    # translate out @distance
    $app.translate @distance, 0 
    $app.stroke 0
    $app.fill 175
    $app.ellipse 0, 0, @diameter, @diameter
    # Once the planet is drawn, the matrix is restored with pop_matrix so that the next planet is not affected.
    $app.pop_matrix 
  end

end


class ObjectOrientedSolarSystemSketch < Processing::App

  def setup
    smooth
    @planets = Array.new(8) { |i| Planet.new(20+i*10, i+8) }
  end

  def draw
    background 255

    # Drawing the Sun
    push_matrix
    # Translate to center of window
    translate width/2, height/2
    stroke 0
    fill 255
    ellipse 0, 0, 20, 20

    # Drawing all Planets
    @planets.each do |p|
      p.update
      p.display
    end

    pop_matrix
  end

end

  ObjectOrientedSolarSystemSketch.new :title => "Object Oriented Solar System", :width => 200, :height => 200

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ruby-processing-1.0.1 samples/learning_processing/chapter_14/18_object_oriented_solar_system.rb
ruby-processing-1.0.2 samples/learning_processing/chapter_14/18_object_oriented_solar_system.rb
ruby-processing-1.0.3 samples/learning_processing/chapter_14/18_object_oriented_solar_system.rb
ruby-processing-1.0.4 samples/learning_processing/chapter_14/18_object_oriented_solar_system.rb