物理エンジンを使う 6, polygon shape を使う

-- 物理エンジンを使う 6, polygon shape を使う
-- Shape のサブクラスには、CircleShape, SegmentShape のほかにもうひとつ PolyShape がある。
require "physics"
   
W, H = platform.window:width(), platform.window:height()
ZERO = physics.Vect(0, 0)

dt         = 0.01   
gravity    = 100
mass       = 1
elasticity = 0.9
friction   = 0.9

leftX,  leftY  = W*0.2, H*0.7 -- 床左端の座標
rightX, rightY = W*0.8, H*0.4 -- 床右端の座標

velX2, velY2  = 0,      0 -- 多角形の初期速度を指定する。
posX2, posY2  = W*0.78, 0 -- 多角形の初期位置を指定する。
  
width, height = 22, 5                 -- 多角形(ここでは矩形)の幅と高さとを指定する。
vertices = {                          -- 多角形の頂点を左回りに指定する。凸形でなければならない。
   physics.Vect(-width/2, -height/2), -- 左上
   physics.Vect(-width/2,  height/2), -- 左下
   physics.Vect( width/2,  height/2), -- 右下
   physics.Vect( width/2, -height/2)  -- 右上
}
x1, y1 = posX2 + vertices[1]:x(), posY2 + vertices[1]:y() -- 最初の描画頂点を指定する。
x2, y2 = posX2 + vertices[2]:x(), posY2 + vertices[2]:y()
x3, y3 = posX2 + vertices[3]:x(), posY2 + vertices[3]:y()
x4, y4 = posX2 + vertices[4]:x(), posY2 + vertices[4]:y()

floorShape = physics.SegmentShape(nil, physics.Vect(leftX, leftY), physics.Vect(rightX, rightY), 0) 
   :setRestitution(elasticity)
   :setFriction(friction)

rectBody = physics.Body(mass, physics.misc.momentForPoly(mass, vertices, ZERO))
   :setVel(physics.Vect(velX2, velY2))
   :setPos(physics.Vect(posX2, posY2))
rectShape = physics.PolyShape(rectBody, vertices, ZERO)
   :setRestitution(elasticity)
   :setFriction(friction)

space = physics.Space()
   :setGravity(physics.Vect(0, gravity))
   :addStaticShape(floorShape)
   :addBody(rectBody)
   :addShape(rectShape)

function on.paint(gc)
      gc:setColorRGB(0x8E8E38)
      gc:drawPolyLine({leftX,leftY,rightX,rightY})
      gc:setColorRGB(0x388E8E)
      gc:fillPolygon({x1,y1,x2,y2,x3,y3,x4,y4})
   end
function on.timer()
   space:step(dt)
   point2 = rectShape:points() -- points() メソッドで多角形の頂点座標を取得する。
   x1, y1 = point2[1]:x(), point2[1]:y()
   x2, y2 = point2[2]:x(), point2[2]:y()
   x3, y3 = point2[3]:x(), point2[3]:y()
   x4, y4 = point2[4]:x(), point2[4]:y()
   platform.window:invalidate()
end
function on.enterKey()
   timer.start(dt)
end