# mousetrack -k
# http://ming.sourceforge.net/examples/example.php?name=mousetrack

require 'ming/ming'
include Ming


use_SWF_version(4)

m = SWFMovie.new
m.set_dimension(320, 240)
m.set_background(0, 0, 0)

# mouse tracking sprite - empty, but follows mouse so we can
# get its x and y coordinates

i = m.add(SWFMovieClip.new)
i.set_name('mouse')

m.add(SWFAction.new("
  startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
"))

# might as well turn off antialiasing, since these are just squares.

m.add(SWFAction.new("
  this.quality = 0;
"))

# morphing box
r = SWFMorph.new
s = r.get_shape1

s.set_left_fill(s.add_fill(0xff, 0xff, 0xff))
s.move_pen_to(-40, -40)
s.draw_line(80, 0)
s.draw_line(0, 80)
s.draw_line(-80, 0)
s.draw_line(0, -80)

s = r.get_shape2

s.set_left_fill(s.add_fill(0x00, 0x00, 0x00))
s.move_pen_to(-1, -1)
s.draw_line(2, 0)
s.draw_line(0, 2)
s.draw_line(-2, 0)
s.draw_line(0, -2)


# sprite container for morphing box -
# this is just a timeline w/ the box morphing

box = SWFMovieClip.new
box.add(SWFAction.new("
  stop();
"))
i = box.add(r)

0.upto(20) do |n|
  i.set_ratio(n/20.0)
  box.next_frame
end


# this container sprite allows us to use the same action code many times

cell = SWFMovieClip.new
i = cell.add(box)
i.set_name('box')

cell.add(SWFAction.new("
  setTarget('box');
  /* ...x means the x coordinate of the parent, i.e. (..).x */
  dx = (/mouse.x + random(120)-60 - ...x)/20;	// without use_SWFVersion(4),
  dy = (/mouse.y + random(120)-60 - ...y)/20;	// Ruby will hang!
  gotoFrame(int(dx*dx + dy*dy));
"))

cell.next_frame
cell.add(SWFAction.new("
  gotoFrame(0);
  play();
"))

cell.next_frame


# finally, add a bunch of the cells to the movie

20.step(320, 40) do |x|
  20.step(240, 40) do |y|
    i = m.add(cell)
    i.move_to(x, y)
  end
end

m.next_frame

m.add(SWFAction.new("
  gotoFrame(1);
  play();
"))

m.save("mousetrack.swf")

