homework7

by Millieyan

HTML

<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://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js"></script>

CSS

body {
    overflow: hidden
}

JavaScript

var camera, scene, renderer, mesh, clock,stats;
var raycaster, pickables = [],allcar = [];
var car;
var wallLength = 200;

var mouse = new THREE.Vector2();

window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousedown', onDocumentMouseDown, false);

class Car {
    constructor(point) {
        point.z = 0;
        this.pos = point.clone();
        this.vel = new THREE.Vector3(0,800, 0);
        this.car = buildVehicle();
        this.car.rotation.x = Math.PI / 2;
        scene.add(this.car);
    }
    update(dt){
    	let x = this.vel.length() * 0.95;
        this.vel.normalize().multiplyScalar(x);
        this.pos.add(this.vel.clone().multiplyScalar(dt));
        this.car.position.copy(this.pos);
    }
   	wallcollision(){
    if(this.pos.x>= wallLength /2-1-5&&this.vel.x>0){
     this.pos.x=wallLength /2-1-5;
    this.vel.x*=-0.9;
    }
     if(this.pos.x<= -wallLength/2+1+5&&this.vel.x<0){
     this.pos.x=- wallLength/2+1+5;
    this.vel.x*=-0.9;
    }
     if(this.pos.y>= wallLength/2-1-5&&this.vel.y>0){
     this.pos.y= wallLength/2-1-5;
    this.vel.y*=-0.9;
    }
    if(this.pos.y<= -wallLength/2+1+5&&this.vel.y<0){
     this.pos.y= -wallLength/2+1+5;
    this.vel.y*=-0.9;
    }
    }
    carcollision(carb) {
    if(this.pos.distanceTo(carb.pos)<10){
    //兩點相撞
    //速度
        
       let caravel = new THREE.Vector3().copy(this.vel);
       let carbvel = new THREE.Vector3().copy(carb.vel);
       let ab = this.pos.clone().sub(carb.pos);
       let ba = ab.clone().multiplyScalar(-1);
       caravel.sub(ab.multiplyScalar(this.vel.clone().sub(carb.vel).dot(ab) / ab.lengthSq()));
       carbvel.sub(ba.multiplyScalar(carb.vel.clone().sub(this.vel).dot(ba) / ba.lengthSq()));

            this.vel.copy(caravel);
            carb.vel.copy(carbvel);
           
   
   //位置
      var delta = this.pos.clone().sub(carb.pos);
      var d=delta.length();
      var diff=(d-10) / d;
      delta.multiplyScalar(0.5 * diff);

     ...