hw4_2
spring-mass-damper system
by KUO YOU-TING
HTML
<div id="info">hw4_2 <br/>
<a href="javascript:reset();">reset</a>
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r70/three.min.js"></script>
CSS
#info {
position: absolute;
top: 0px;
width: 100%;
padding: 10px;
text-align: center;
color: #ffff00
}
body {
overflow: hidden;
}
JavaScript
var camera, scene, renderer;
var mesh, border;
var mouse = new THREE.Vector2();
var clock = new THREE.Clock();
var lineGroup, q0, q1;
var m = 1, k = 5, c = .0, fc = 0;
var x = [], p, u, v = [];
function TwoPointLine (q0, q1) {
lineGroup = new THREE.Object3D();
// build the line
var geometry = new THREE.Geometry();
geometry.vertices.push (q0.clone(), q1.clone());
lineGroup.add (new THREE.Line (geometry, new THREE.LineBasicMaterial()));
// add two end points
var point;
point = new THREE.Mesh(new THREE.CircleGeometry(1, 12), new THREE.MeshBasicMaterial());
point.position.copy(q0);
lineGroup.add(point);
point = new THREE.Mesh(new THREE.CircleGeometry(1, 12), new THREE.MeshBasicMaterial());
point.position.copy(q1);
lineGroup.add(point);
return lineGroup;
}
function reset() {
x[0] = 20, x[1] = 0;
}
function deriv (x) {
var ff = [];
ff.push (x[1]); // x_dot = v;
if (fc === 0)
ff.push (-(c*x[1] + k*x[0])/m); // v_dot = 1/m *(-cx_dot -kx)
else if (fc === 1) {
u = Math.sqrt(Math.pow(p[0]-x[0], 2) + Math.pow(p[1], 2));
if(p[0] > x[0])
u *=-1;
ff.push (-(c*x[1] + k*x[0] + u*k)/m);
}
return ff;
}
function ODESolver (dt) {
var n = x.length;
var f = deriv(x);
for(var i = 0; i < n; i++)
v[i] = x[i] + f[i] * (dt/2);
f = deriv(v);
for(var i = 0; i < n; i++)
x[i] += f[i] * dt;
/*
this.time = this.time + dt || 0;
x[0] = 20*Math.sin(5*this.time); // fake....
*/
}
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.OrthographicCamera(-50, 50, 50, -50, -10, 10);
camera.position.z = 10;
scene.add(camera);
mesh = new THREE.Mesh(new THREE.CircleGeometry(1, 10), new THREE.MeshBasicMaterial());
scene.add(mesh);
var material = new THREE.LineBasicMaterial({
color: 0x0000ff
});
var geometry = new THREE.Geometry();
...