hw4 prototype

seek

by Rebecca Chen

HTML

<div id="info">hw4 helper (collision)</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r70/three.min.js"></script>
<script src="https://dl.dropboxusercontent.com/u/3587259/Code/Threejs/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

var camera, scene, renderer, controls;
var puck;
var agent;

var mass = 1;
var clock = new THREE.Clock();

var obCen = new THREE.Vector3();
var obRad = 50;

var target = new THREE.Vector3();

var Agent = function(mesh, initPos) {
  this.pos = new THREE.Vector3();
  if (initPos) this.pos.copy(initPos);

  this.vel = new THREE.Vector3();
  this.force = new THREE.Vector3();
  this.target = new THREE.Vector3();
  this.angle = 0
  this.mesh = mesh;
  this.maxSpeed = 60;
  this.maxForce = 60;

  this.setTarget = function(target) {
    this.target.copy(target);
  }

  this.update = function(dt) {
    // compute force
    this.force = this.target.clone().sub(this.pos).setLength(this.maxSpeed).sub(this.vel);

		// collision avoidance
    // (for each obstacle)
    var tmp = obCen.clone().sub(this.pos);
    var tmpProj = tmp.clone().projectOnVector(this.vel);
    
    //console.log (tmp.dot(this.vel));
    
    if (tmp.dot(this.vel) > 0) {
    	if (tmpProj.clone().sub(tmp).length() < obRad + 3) {
      	
      	if (tmpProj.length() < 5 *this.vel.length()) {
        	console.log ('block & close');
    			this.force.add (tmpProj.clone().sub(tmp).multiplyScalar(2));    	
        }
      }
    }  

		// force clamping
    if (this.force.length() > this.maxForce)
      this.force.setLength(this.maxForce);
    this.vel.add(this.force.clone().multiplyScalar(dt));

    // velocity clamping
    if (this.vel.length() > this.maxSpeed)
      this.vel.setLength(this.maxSpeed);
    this.pos.add(this.vel.clone().multiplyScalar(dt));

    if (this.vel.length() > 0.001) {
      this.angle = Math.atan2(-this.vel.z, this.vel.x);
    }
    this.mesh.position.copy(this.pos);
    this.mesh.rotation.y = this.angle;

    // catch handling
    if (this.pos.distanceTo(this.target) < 2) {
      this.vel.set(0, 0, 0);
      angle = Math.random() * Math.PI * 2;
		}

    
    
  }
}

init();
animate();

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

  camera = new THREE.PerspectiveCamera(50,...