agent

seek, arrival

by 蔡 育曄

HTML

<div id="info">Agent (Seek, Arrival, Collision)</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>

CSS

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

body {
  overflow: hidden
}

JavaScript

class Obstacle {
	constructor (center,size) {
		this.center = center.clone();  
		this.mesh = new THREE.Mesh (new THREE.CylinderGeometry(size,size,1,20),
			new THREE.MeshBasicMaterial());
		this.mesh.position.copy (center);
		this.size = size;
    scene.add (this.mesh)
	}
}

class Agent {
  constructor(pos, mesh) {
    this.pos = pos.clone();
    this.vel = new THREE.Vector3();
    this.force = new THREE.Vector3();
    this.target = new THREE.Vector3();
    this.size = 3;  // half width
    this.mesh = mesh;
    this.MAXSPEED = 50;
    this.ARRIVAL_R = 30;
    //this.nbhd = [];
    
    // for orientable agent
    this.angle = 0;
  }
  update(dt) {
    this.accumulateForce();
//    this.vel.add(this.force.clone().multiplyScalar(dt));
    
	// collision
	let vhat = this.vel.clone().normalize();
	//let point = ob.center.clone().sub (this.pos) // c-p
  var point = obs[0].center.clone().sub (this.pos) // c-p
	var proj  = point.dot(vhat);
  var id = 0;
  for(let i = 1; i < obs.length; i++) {
  	let pt = obs[i].center.clone().sub (this.pos);
    let pj = pt.dot(vhat);
    if( pj > 0  && pj< Math.abs(proj) ) {
      proj = pj;
      id = i;
    }
  }
  point = obs[id].center.clone().sub (this.pos) // c-p
	proj  = point.dot(vhat);
  console.log(id)
  console.log(proj)
	const REACH = 50;
	const K = 50;
	if (proj > 0 && proj < REACH) {
		let perp = new THREE.Vector3();
		perp.subVectors (point, vhat.clone().setLength(proj));
		//let overlap = ob.size + this.size - perp.length()
    let overlap = obs[id].size + this.size - perp.length()
    if (overlap > 0) {
			perp.setLength (K*overlap);
			perp.negate()
      this.force.add (perp);
			console.log ("hit:", perp);
		}
	}
  
  this.vel.add(this.force.clone().multiplyScalar(dt));

    
    // velocity modulation
    let diff = this.target.clone().sub(this.pos)
    let dst = diff.length();
    if (dst < this.ARRIVAL_R) {
      this.vel.setLength(dst)
    }
    
    
    this.pos.add(this.vel.clone().multiplyScalar(dt))
   ...