agent

seek, arrival

by Leoooo

HTML

<div id="info">Agent (Seek, Arrival)</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/107/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

// IIFE addition of clamp function
( function( ) {
      Math.clamp = function(val,min,max) {
          return Math.min(Math.max(val,min),max);
      } 
} )();

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;
    this.mesh = mesh;
    this.MAXSPEED = 50;
    this.ARRIVAL_R = 30;
    
    // for orientable agent
    this.angle = 0;
  }
  
  update(dt) {
    this.accumulateForce();
    this.vel.add(this.force.clone().multiplyScalar(dt));

		// ARRIVAL: velocity modulation
    let diff = this.target.clone().sub(this.pos)
    let dst = diff.length();
    if (dst < this.ARRIVAL_R) {
      this.vel.setLength(dst)
    }
   
   	// MAXSPEED modulation
		let speed = this.vel.length()
		this.vel.setLength(Math.clamp (speed, 0, this.MAXSPEED))
		this.pos.add(this.vel.clone().multiplyScalar(dt))
    this.mesh.position.copy(this.pos)
    
    // for orientable agent
    // non PD version
    if (this.vel.length() > 0.1) {
	    	this.angle = Math.atan2 (-this.vel.z, this.vel.x)
    		this.mesh.rotation.y = this.angle
   	}
  }
  setTarget(target) {
    this.target.copy(target)
  }
  targetInducedForce(targetPos) {
    return targetPos.clone().sub(this.pos).normalize().multiplyScalar(this.MAXSPEED).sub(this.vel)
  }

  accumulateForce() {
    // seek
    this.force.copy(this.targetInducedForce(this.target));
  }

}


////////////////////
var camera, scene, renderer;
var puck;

var raycaster;
var mouse = new THREE.Vector2();
var pickables = [];

init();
animate();

function agentMesh () {
	// mesh facing +x
	let geometry = new THREE.Geometry();
  geometry.vertices.push (new THREE.Vector3(10,0,0))
  geometry.vertices.push (new THREE.Vector3(0,0,-3))
  geometry.vertices.push (new THREE.Vector3(0,0,3))
  geometry.vertices.push (new THREE.Vector3(0,3,0))
  
  geometry.faces.push(new THREE.Face3(0, 3, 2));
  geometry.faces.push(new...