Collision Disk

by jason870509

HTML

<div id="info">hw2 helper<br>
  <button id="play" style="width:20%">Play</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/109/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 Ball {
  constructor(mesh, rad = 2) {

    this.pos = new THREE.Vector3()
    this.vel = new THREE.Vector3()
    this.force = new THREE.Vector3()
    this.mesh = mesh;
    this.radius = rad;
    this.color = this.mesh.material.color.setHSL(Math.random(), 1, 0.5)
    //this.mesh.material.color.setHSL ( Math.random(), 1, 0.5 )
    //thiis.color.setHSL ( Math.random(), 1, 0.5 )
    this.light = new THREE.PointLight(this.color, 1, 50);
    scene.add(this.light)
    scene.add(this.mesh) // add to scene when particle is created

    //this.mesh.material.color.copy(this.color);

  }
  update(dt, i) {
    this.vel.add(this.force.clone().multiplyScalar(dt))
    this.pos.add(this.vel.clone().multiplyScalar(dt))
    this.i = i
    this.collidingPlanes(planes)
    this.collidingBalls();
    this.mesh.position.copy(this.pos)
    this.light.position.copy(this.pos)
    this.light.position.y += 20
  }
  collidingBalls() {
    for (var k = 0; k < balls.length; k++) {
      if (this.i == k) continue;
      let ball2 = balls[k];
      var dis = Math.sqrt((this.pos.x - ball2.pos.x) * (this.pos.x - ball2.pos.x) + (this.pos.z - ball2.pos.z) * (this.pos.z - ball2.pos.z));
      // console.log(dis)
      if (dis < 20) {
        console.log("hit")
        //soundVal += sign*0.01;
        //collisionSound.play();
        //soundVal = THREE.Math.clamp (soundVal, 0, 1);
        //soundtrack.volume = soundVal;
        //console.log(ball1.mesh.localToWorld(new THREE.Vector3(0, 0, 0)))
        var middleX = Math.abs(this.mesh.position.x + ball2.mesh.position.x) / 2
        var middleY = Math.abs(this.mesh.position.z + ball2.mesh.position.z) / 2
        /*if (ball1.mesh.position.x < middleX) {
          if (ball1.mesh.position.z < middleY) {
            ball1.mesh.position.x -= 1
            ball1.mesh.position.z -= 1
            ball2.mesh.position.x += 1
            ball2.mesh.position.z += 1
          } else {
            ball1.mesh.position.x -= 1
            ball1.mesh.position.z +=...