Homework7

by wayne6172

HTML

<div id = "title">Hw7 Demo</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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js"></script>

CSS

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

JavaScript

var camera, scene, renderer, mesh, line, stats, clock;
var raycaster, pickables = [];

var 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, 500, 0);

        this.car = buildVehicle();
        this.car.rotation.x = Math.PI / 2;
        scene.add(this.car);
    }

    checkWall() {
        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.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;
        }

    }

    checkCollision(anotherCar) {
        if (this.pos.distanceTo(anotherCar.pos) < 5.0 + 5.0) {
            //--------------位置修正---------------//

            var delta = this.pos.clone().sub(anotherCar.pos);
            var d = delta.length();
            var diff = (10.0 - d) / d;

            delta.multiplyScalar(0.5 * diff);

            this.pos.add(delta);
            anotherCar.pos.sub(delta);

            //-----------------速度修正-----------------

            let nextV1 = new THREE.Vector3().copy(this.vel);
            let nextV2 = new THREE.Vector3().copy(anotherCar.vel);

            let X1_Sub_X2 = this.pos.clone().sub(anotherCar.pos);
            let X2_Sub_X1 = X1_Sub_X2.clone().multiplyScalar(-1);
           ...