20. Optimisation and an experiment.

function setup(){
  tmax=600;
  ScaleWindow(-1.2,-0.3,1.2,0.3);

  Colour('blue');       //draw seesaw
  MoveTo(-1.2,-0.13);
  LineTo(1.2,-0.13);
  MoveTo(0,0);
  LineTo(-0.1,-0.13);
  MoveTo(0,0);
  LineTo(0.1,-0.13);

  kx=document.getElementById("posgain").value*1.0;
  kv=document.getElementById("vgain").value*1.0;   
  vdemlim=document.getElementById("vellim").value*1.0; 
  interval=document.getElementById("tint").value; 

  dt=.01;
  t=0;
  twaiting=0;
  stepdem=0;
  tiltdem=0;
  veldem=0;
  v=0;
  x=0;
  tilt=0;
  steps=-50;
  radperstep=1/400;
  stepdem=0;
  stepmax=50;
  cos=1;
  sin=0;
  drawit();
  loop();
} 

function loop(){
  if(twaiting<0){
    twaiting=interval;
    whichway=k0*(x-xtarget)+k1*x1+k2*x2-angle;
    steps+=Math.sign(whichway);
    angle+=Math.sign(whichway)-angle/decay;
    steps=limit(steps,50);
    
    x2=x1;
    x1=x-xtarget;
  }
  twaiting-= dt;
  ctx.lineWidth=3;
  drawit('ivory');
  cos=Math.cos(steps*radperstep);
  sin=Math.sin(steps*radperstep);
  v= v-4*sin*dt;  
  if((Math.abs(x)>1)&&(x*v>0)){v=0;}
  x= x+v*dt;                  //This is the simulation
  t= t+dt;
  vdem=limit(kx*(stepdem/50-x),vdemlim);
  tiltdem=(v-vdem)*kv;
  if(manual){tiltdem=stepdem;}

  ctx.lineWidth=1;
  drawit("black");

    if(t<tmax){setTimeout("loop();", 10);}
}
function limit(a,b){
var temp=a;
if(a>b){temp=b;}
if(a<-b){temp=-b;}
return temp;
}
function drawit(c){
  Colour(c);
  MoveTo(-cos,-sin);
  LineTo(cos,sin);
  ctx.beginPath();
  ctx.arc(x*cos*xsc,x*sin*ysc-10,10,0,6.3);
  ctx.stroke();
}