(42)惑星(衛星)の運動 4

platform.apilevel = "2.4"

local slateblue = 0x7171C6
local salmon = 0xC67171
local brightgray = 0xC5C1AA
local lightsteelblue = 0xCAE1FF
local dodgerblue = 0x104E8B

platform.window:setBackgroundColor(dodgerblue)

local time = 0 -- シム内経過時間〔sec〕
local step = 0.1 --〔sec〕

function on.resize()
   w, h = platform.window:width(), platform.window:height()
   x0, y0 = w/5, h/2 -- 原点を設定
   unit = h/10 -- 画面上での 1 単位の画素数
   radius_center = h/20 -- 中心質点の半径
   dia_center = radius_center * 2 -- 中心質点の直径
   radius_sat = h/40 -- 移動体の半径
   dia_sat = radius_sat * 2 -- 移動体の直径
   fontSize = math.floor(h/17)
end

var.store("gm", 9.8)
var.store("tstart", 0)
var.store("tstop", step)
var.store("ini_lx", -1) -- x 方向の初期位置
var.store("ini_vx", 0) -- x 方向の初速
var.store("ini_ly", 0) -- y 方向の初期位置
var.store("ini_vy", 4.2) -- y 方向の初速
var.store("step", step)
var.store("tol", 0.001)

--- 中心座標と半径と直径とで円を描く部分プログラム(円の中心座標, 半径, 直径, 色, gc)
function drawCircle(x, y, radius, dia, color, gc)
   gc:setColorRGB(color)
   gc:fillArc(x - radius, y - radius, dia, dia, 0, 360)
end

function on.paint(gc)
   gc:setPen("thin")
   gc:setFont("sansserif", "r", fontSize)

   -- rk23() を計算
   mat = math.eval("satellite(gm, tstart, tstop, ini_lx, ini_vx, ini_ly, ini_vy, step, tol)")
   
   -- 移動体の座標を計算する
   x1 = x0 + unit * mat[2][1]
   y1 = y0 - unit * mat[4][1]
   
   -- 中心質点と移動体とを結ぶ直線を描く
   gc:setColorRGB(slateblue)
   gc:drawLine(x0, y0, x1, y1)

   -- 移動体を描画する
   drawCircle(x1, y1, radius_sat, dia_sat, lightsteelblue, gc)
      
   -- 原点に中心質点を描画する
   drawCircle(x0, y0, radius_center, dia_center, salmon, gc)
   
   -- シム内の経過時間を表示
   gc:setColorRGB(brightgray)
   gc:drawString("time = "..math.floor(time).." s", fontSize, fontSize)
end

function on.enterKey()
   timer.start(0.01)
end
function on.escapeKey()
   timer.stop()
end
function on.timer()
   platform.window:invalidate()
   
   --「次の値」を初期値に入れ換える
   var.store("ini_lx", mat[2][2])
   var.store("ini_vx", mat[3][2])
   var.store("ini_ly", mat[4][2])
   var.store("ini_vy", mat[5][2])
   time = time + step
end