collision

by Bai Shiuan Huang

HTML

<div id="info">cylinder-sphere CONTINUOUS collision 
<br><input type=range min=0 max=50 value = 40 id='move'> interpolate <br>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js">


</script>

<!------------------------------------------------------------------->
<script src="https://code.jquery.com/jquery-2.1.4.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, light, controls;
//var keyboard = new KeyboardState();
var ball, ball1, ball2, cylinder;
var R = 3; // ball radius
var r = 10; // cylinder radius
var h = 20; // cylinder height

/*$('#move').change (function() {
	ball.position.lerpVectors (ball1.position, ball2.position, $(this).val()/50)
});*/

init();
animate();

function ballsCylinderInter () {
	let u = new THREE.Vector3();
  let v = new THREE.Vector3();
  
   
  u.set (ball2.position.x - ball1.position.x, 0, ball2.position.z - ball1.position.z)
  v.set (cylinder.position.x - ball1.position.x, 0,
  				cylinder.position.z - ball1.position.z)
 	let dd = u.sub(u.clone().projectOnVector(v)).length();
  console.log ('dd: ' + dd)
  if ( u.sub(u.clone().projectOnVector(v)).length() > r+R ) return

	if (ball1.position.y > h+R && ball2.position.y > h+R) return
	if (ball1.position.y < h+R && ball2.position.y < h+R) alert ('hit')
  
	// (1-t)*b1y + t*b2y = h+R
  // [consider divide-by-zero]
  
  let t = (h+R - ball1.position.y)/(ball2.position.y - ball1.position.y);
  let inter = ball1.position.clone().multiplyScalar (1-t).add ( ball2.position.clone().multiplyScalar(t) );
  console.log (inter)
  let cc = cylinder.position.clone();
  cc.y = h+R;
  let ddd = cc.distanceTo (inter) 
  console.log (cc)
  console.log (ddd)
  if (cc.distanceTo (inter) < r+R) {
  	alert ('intersect!')
  } 
          
}

function ballCylinderInter() {
  let point = ball.position.clone().sub(cylinder.position);
  let yp = new THREE.Vector3(0, 1, 0)
  let hh = point.dot(yp);
  if (hh < h + R && (point.lengthSq() - hh * hh) < (r + R) * (r + R)) {
    ball.material.color = new THREE.Color('red')
  //  console.log ('hh:' + hh)
  } else 
    ball.material.color = new THREE.Color('white')
  
}

function init() {
  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000);
  camera.position.z = 150;
  scene.add(camera);

  light = new THREE.PointLight(0xffffff);
 ...