Kopiere die Datei Sim.js in ein beliebiges Verzeichnis. Für die folgende Beschreibung wird angenommen, dass sich die Datei im selben Verzeichnis wie die Webseite befindet.
<script src="x.js" type="text/javascript"></script> <script src="Sim.js" type="text/javascript"></script>
<script type="text/javascript"> var MySim = new Sim( Parameters ); : </script>
Das folgende Beispiel zeigt exemplarisch, wie mit dem Sim gearbeitet werden kann. Es ist ein Auschnitt des Codes der Demo.
var PendulumModel = {
v0: 4, // start speed
a: 0, // current angle
da: 0, // current angular speed
dda: 0, // current angular acceleration
d1: 0, // linear damping
d2: 0.1, // quadratic damping
m: 1, // pendulum mass
l: 1, // pendulum length
g: 9.81, // gravitational acceleration
Fl: 0, // current string force
Fg: 0, // current gravity force
Fd: 0, // current damping force
Ft: 0, // current total force
graph: null,
sim: null,
Create: function( sim ) {
this.sim = sim;
var me = this;
this.graph = NewGraph2D( {
Id: 'PendulumModel-Graph',
Width: '100%',
Height: '60%',
DrawFunc: function(){ me.Draw(); },
OnClick: function(){ sim.Pause(true); },
AutoReset: false,
AutoClear: false,
} );
},
Reset: function() {
this.a = 0;
this.da = this.v0;
this.dda = 0;
},
Update: function() {
// is called from sim to compute next time step values
// compute all forces
this.Fg = this.m * this.g;
this.Fl = this.Fg * Math.cos( this.a );
this.Fd = this.d1 * Math.abs( this.da ) + this.d2 * this.da * this.da;
var vdir = this.da >= 0 ? -1 : 1;
this.Ft = -this.Fg * Math.sin( this.a ) + vdir * this.Fd;
// compute new acceleration, speed and position by simple numerical integration
this.dda = this.Ft / this.m;
this.da += this.dda * this.sim.DeltaTime;
this.a += this.da * this.sim.DeltaTime;
},
Draw: function() {
// is called from sim once per frame to draw pendulum
var g = this.graph;
g.Reset();
g.MapWindow( 0, 0.5, 2.2, 0, 0 );
// compute pendulum position
var x = this.l * Math.sin( this.a );
var y = -this.l * Math.cos( this.a ) + 1;
// draw pendulum
g.SetLineAttr( 'black', 2 );
g.Line( 0, 1, x, y );
g.SetMarkerAttr( 'Circle', 20, 'black', 'yellow', 2 );
g.Marker( x, y );
// draw zero marker
g.SetMarkerAttr( 'ArrowUp', 10, 'black', 'white', 1 );
g.Marker( 0, -0.04 );
},
};
var PendulumSim = new Sim( {
SimObj: PendulumModel,
ResetFuncs: function(sim) { sim.SimObj.Reset(); },
TimeStepFuncs: function(sim) { sim.SimObj.Update(); },
FrameFuncs: function(sim) { sim.SimObj.Draw(); },
} );
PendulumModel.Create( PendulumSim );
PendulumSim.Run( true );