three.js testbed

with orbitControls, XZgrid, info

by 蔡 育曄

HTML

<div id="info">hw2 helper
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js">
</script>
<script src="https://jyunming-chen.github.io/tutsplus/js/KeyboardState.js"></script>

CSS

#info {
  position: absolute;
  top: 0px;
  width: 100%;
  padding: 10px;
  text-align: center;
  color: #ffff00
}

body {
  overflow: hidden;
}

JavaScript

class Particle {
	constructor (mesh, color, rad = 10) {
  
  	this.pos = new THREE.Vector3();
    this.prevPos = new THREE.Vector3();
    this.vel = new THREE.Vector3();
    this.force = new THREE.Vector3();
    this.mesh = mesh;
    this.radius = rad;
    this.light = new THREE.PointLight (color, 1.8, 100);
    scene.add (this.light)
    scene.add (this.mesh)   // add to scene when particle is created

//console.log (color)
		this.mesh.material.color.copy ( color );
    this.mesh.material.emissive.copy(color);
  }
  update (dt) {
    this.prevPos.copy(this.pos);
		this.vel.add (this.force.clone().multiplyScalar (dt))
  	this.pos.add (this.vel.clone().multiplyScalar(dt))
    
		this.collidingPlanes (planes);
    this.collidingParticles(particles);
    this.collidingWalls(walls);
    // simple collision
  /*
  if (this.pos.z > 100 - this.radius) {
    	const CR = 0.9
    	this.pos.z = 100 - this.radius
      this.vel.z = - CR * this.vel.z;
    }
  */  
		this.mesh.position.copy (this.pos)
    this.light.position.copy (this.pos)
    this.light.position.y += 20
  }

	collidingPlanes (planes) {
    const EPS = 1e-3
    const CR = 0.96
  	for (let i = 0; i < planes.length; i++) {
			let plane = planes[i]
			let point = this.pos.clone().sub (plane.ptOnPl)
      if ( point.dot(plane.normal) < EPS + this.radius) {
				// position correction
      	this.pos.copy (plane.ptOnPl.clone().add (point.projectOnPlane(plane.normal)) )
        this.pos.add (plane.normal.clone().multiplyScalar(this.radius))
      	// velocity update
      	this.vel.sub (plane.normal.clone().multiplyScalar ((1+CR)*this.vel.dot(plane.normal)))
      	//return;  // assume particle collides with AT MOST one plane
      }
  	}
  }

  collidingParticles(particles) {
    const EPS = 1e-3;
    for (let i = 0; i < particles.length; i++) {
      let particle = particles[i];
      let distance = this.pos.distanceTo(particle.pos);
      //console.log(this.vel)

      if(distance < this.radius +particle.radius&&...