Homework8.1

by wayne6172

HTML

<div id="title">用WASD控制速度與方向,方向鍵控制砲管,空白鍵射擊</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>

<script src="https://jyunming-chen.github.io/tutsplus/js/KeyboardState.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, controls, stats, clock;
var keyboard = new KeyboardState();
var k = 4;

var tank;

window.addEventListener('resize',onWindowResize,false);

(function() {
    Math.clamp = function(val, min, max) {
        return Math.min(Math.max(val, min), max);
    }
})();

class Shell {
    constructor(pos, vel) {
        this.speed = 25.0;
        this.V0 = vel.clone().normalize().multiplyScalar(this.speed);
        this.Vg = new THREE.Vector3(0, this.V0.y, 0);
        this.V0.y = 0;

        this.pos = pos.clone();
        this.body = new THREE.Mesh(new THREE.SphereGeometry(1.5, 32, 32), new THREE.MeshNormalMaterial());

        this.body.position.copy(this.pos);
        scene.add(this.body);
    }

    destroy() {
        scene.remove(this.body);
    }

    update(dt) {
        this.Vg.sub(new THREE.Vector3(0, 9.8, 0).multiplyScalar(dt));
        var vel = this.V0.clone().add(this.Vg);
        this.pos.add(vel.clone().multiplyScalar(dt));

        if (this.pos.y <= 1.5) {
            this.destroy();
            return false;
        }

        this.body.position.copy(this.pos);
        return true;
    }
}

class Tank {
    constructor() {
        this.bodySpeed = 1.0;
        this.bodyAngle = 0.0;
        this.turretAngle = 0.0;
        this.cannonAngle = 0.0;
        this.shell = [];
        this.muzzle = new THREE.Object3D();
        this.body = this.createBody();
        this.turret = this.createTurret();
        this.cannon = this.createCannon();

        this.muzzle.position.x = 10;
        //this.muzzle.add(new THREE.AxisHelper(5));
        this.cannon.add(this.muzzle/*, new THREE.AxisHelper(5)*/);
        this.cannon.position.x = 10;
        this.turret.add(this.cannon/*, new THREE.AxisHelper(5)*/);
        this.turret.position.set(10, 10, 0);
        this.body.add(this.turret/*, new THREE.AxisHelper(5)*/);
        this.body.position.set(0, 5, 0);
        scene.add(this.body);
    }

    createBody() {
        var body = new...