three实现高速公路赛车游戏代码

代码语言:html

所属分类:游戏

代码描述:three实现高速公路赛车游戏代码

代码标签: three 高速 公路 赛车 游戏 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Muli:400,700,900&amp;display=swap'>

<style>
    * {
	border: 0;
	box-sizing: border-box;
	margin: 0;
	padding: 0;
}
:root {
	font-size: calc(16px + (20 - 16) * (100vw - 320px)/(1024 - 320));
}
body, button {
	color: #fff;
	font: 1em Muli, "Helvetica Neue", Helvetica, sans-serif;
	line-height: 1.5;
}
body {
	overflow: hidden;
}
button, canvas {
	-webkit-tap-highlight-color: transparent;
}
button, .difficulty-select, .tutorial {
	opacity: 0;
}
button {
	background: #2762f3;
	border-radius: 0.375em;
	box-shadow: 0 0 0 0.25em inset, 0 -0.5em 0 #0003 inset;
	cursor: pointer;
	display: block;
	font-weight: 700;
	margin: 0 auto 0.75em auto;
	padding: 0.75em 1.5em;
	transition: background 0.15s linear;
	transform: translateY(50%);
	width: 100%;
	max-width: 16em;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
}
button:hover {
	background: #5785f6;
}
button:active {
	background: #0c48db;
}
button:disabled {
	cursor: default;
}
header, .difficulty-select, .tutorial, .replay {
	position: absolute;
	z-index: 1;
}
header, .difficulty-select {
	left: 0;
	width: 100%;
}
header, h1 {
	line-height: 1;
}
header {
	font-size: 4em;
	font-weight: 900;
	top: 0;
	padding: 0.75rem;
	-webkit-text-stroke: 4px #171717;
	text-shadow: 0 4px 0 #171717;
	transform: translateY(-100%);
	transition: all 0.25s linear;
}
h1 {
	font-size: 2em;
	margin-bottom: 1em;
	text-align: center;
	transform: translateX(100%);
}
kbd {
	background: #242424;
	border-radius: 0.25em;
	display: inline-block;
	font-family: Helvetica, sans-serif;
	height: 1.5em;
	min-width: 1.5em;
	padding: 0 0.25em;
	text-align: center;
	vertical-align: middle;
}
p {
	margin-bottom: 1.5em;
}

/* UI */
.difficulty-select, .tutorial, .replay {
	top: 50%;
}
.difficulty-select, .tutorial {
	background: #0000007f;
}
.difficulty-select {
	padding: 1.5em 0;
	transform: translateY(-50%);
}
.menu-active, .tutorial-active, .replay-active {
	z-index: 9;
}
.menu-active {
	animation: fadeIn 0.5s linear forwards;
}
.menu-active h1 {
	animation: slideIn 0.5s 0.5s linear forwards;
}
.menu-active button:nth-of-type(1) {
	animation: fadeSlide 0.15s 1s linear forwards;
}
.menu-active button:nth-of-type(2) {
	animation: fadeSlide 0.15s 1.15s linear forwards;
}
.menu-active button:nth-of-type(3) {
	animation: fadeSlide 0.15s 1.3s linear forwards;
}
.menu-active button:nth-of-type(4) {
	animation: fadeSlide 0.15s 1.45s linear forwards;
}
.menu-inactive {
	animation: fadeIn 0.5s 1.1s linear reverse forwards;
	opacity: 1;
}
.menu-inactive h1 {
	animation: slideOut 0.5s 0.6s linear forwards;
	transform: translateX(0);
}
.menu-inactive button {
	opacity: 1;
	transform: translateY(0);
}
.menu-inactive button:nth-of-type(1) {
	animation: fadeSlide 0.15s linear reverse forwards;
}
.menu-inactive button:nth-of-type(2) {
	animation: fadeSlide 0.15s 0.15s linear reverse forwards;
}
.menu-inactive button:nth-of-type(3) {
	animation: fadeSlide 0.15s 0.3s linear reverse forwards;
}
.menu-inactive button:nth-of-type(4) {
	animation: fadeSlide 0.15s 0.45s linear reverse forwards;
}
.tutorial {
	border-radius: 0.75em;
	padding: 1.5em 1.5em 0 1.5em;
	left: 50%;
	text-align: center;
	width: 12em;
	transform: translate(-50%,-50%);
	transition: opacity 0.25s linear;
}
.replay {
	margin: 0;
	padding: 1.5em;
	left: 50%;
	transform: translate(-50%,0);
	transition: all 0.15s linear;
	width: 6em;
	height: 6em;
}
.btn-icon {
	fill: #fff;
	width: 3em;
	height: 3em;
}
.score-active {
	transform: translateY(0);
}
.tutorial-active, .replay-active {
	opacity: 1;
}
.replay-active {
	transform: translate(-50%,-50%);
}

/* Animations */
@keyframes fadeIn {
	from { opacity: 0 }
	to { opacity: 1 }
}
@keyframes slideIn {
	from { transform: translateX(100%) }
	to { transform: translateX(0) }
}
@keyframes slideOut {
	from { transform: translateX(0) }
	to { transform: translateX(-100%) }
}
@keyframes fadeSlide {
	from {
		opacity: 0;
		transform: translateY(50%);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}
</style>
</head>

<body>
    <!-- partial:index.partial.html -->
    <header>0</header>
    <div class="difficulty-select">
        <h1>Select Difficulty</h1>
        <button type="button" data-difficulty="0" disabled>Easy</button>
        <button type="button" data-difficulty="1" disabled>Medium</button>
        <button type="button" data-difficulty="2" disabled>Hard</button>
        <button type="button" data-difficulty="3" disabled>Brutal</button>
    </div>
    <div class="tutorial">
        <p><strong>Steer:</strong></p>
        <p><kbd>A</kbd> <kbd>D</kbd><br>or<br><kbd>&#8592;</kbd> <kbd>&#8594;</kbd><br>or<br>Drag left/right</p>
    </div>
    <button type="button" class="replay" disabled>
	<svg class="btn-icon" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="96px" height="96px" viewBox="0 0 96 96" enable-background="new 0 0 96 96">
		<path d="M96,88V60c0-1.083-0.396-2.021-1.188-2.812C94.02,56.396,93.083,56,92,56H64c-1.75,0-2.979,0.833-3.688,2.5
c-0.709,1.625-0.418,3.062,0.875,4.312l8.625,8.625C63.645,77.145,56.374,79.999,48,79.999c-4.333,0-8.469-0.844-12.406-2.531
c-3.937-1.687-7.344-3.969-10.219-6.844s-5.156-6.281-6.844-10.219C16.843,56.467,16,52.332,16,47.999
c0-4.334,0.844-8.469,2.531-12.406c1.687-3.937,3.969-7.344,6.844-10.219s6.281-5.156,10.219-6.844
c3.938-1.688,8.073-2.531,12.406-2.531c7.042,0,13.375,2.072,19,6.219c5.625,4.147,9.479,9.595,11.562,16.345
C78.854,39.521,79.479,40,80.438,40h12.438c0.667,0,1.188-0.25,1.562-0.75c0.416-0.541,0.562-1.104,0.438-1.688
c-1.625-7.291-4.698-13.791-9.219-19.5C81.135,12.354,75.594,7.916,69.031,4.75C62.468,1.584,55.458,0,48,0
c-6.5,0-12.708,1.271-18.625,3.812s-11.021,5.959-15.312,10.25s-7.708,9.396-10.25,15.312S0,41.5,0,48s1.271,12.708,3.812,18.625
s5.958,11.021,10.25,15.312s9.396,7.707,15.312,10.25C35.29,94.729,41.5,96,48,96c6.125,0,12.052-1.156,17.781-3.469
c5.729-2.313,10.822-5.573,15.281-9.781l8.125,8.062c1.207,1.291,2.666,1.582,4.375,0.875C95.188,90.979,96,89.75,96,88z"/>
	</svg>
</button>
    <!-- partial -->
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/three.109.js"></script>     
    <script >
        "use strict"

// ## License
// 
// Copyright (c) 2011 Evan Wallace (http://madebyevan.com/), under the MIT license.
// THREE.js rework by thrax


// # class CSG
// Holds a binary space partition tree representing a 3D solid. Two solids can
// be combined using the `union()`, `subtract()`, and `intersect()` methods.

class CSG {
    constructor() {
        this.polygons = [];
    }
    clone() {
        var csg = new CSG();
        csg.polygons = this.polygons.map(function(p) {
            return p.clone();
        });
        return csg;
    }

    toPolygons() {
        return this.polygons;
    }

    union(csg) {
        var a = new Node(this.clone().polygons);
        var b = new Node(csg.clone().polygons);
        a.clipTo(b);
        b.clipTo(a);
        b.invert();
        b.clipTo(a);
        b.invert();
        a.build(b.allPolygons());
        return CSG.fromPolygons(a.allPolygons());
    }

    subtract(csg) {
        var a = new Node(this.clone().polygons);
        var b = new Node(csg.clone().polygons);
        a.invert();
        a.clipTo(b);
        b.clipTo(a);
        b.invert();
        b.clipTo(a);
        b.invert();
        a.build(b.allPolygons());
        a.invert();
        return CSG.fromPolygons(a.allPolygons());
    }

    intersect(csg) {
        var a = new Node(this.clone().polygons);
        var b = new Node(csg.clone().polygons);
        a.invert();
        b.clipTo(a);
        b.invert();
        a.clipTo(b);
        b.clipTo(a);
        a.build(b.allPolygons());
        a.invert();
        return CSG.fromPolygons(a.allPolygons());
    }

    // Return a new CSG solid with solid and empty space switched. This solid is
    // not modified.
    inverse() {
        var csg = this.clone();
        csg.polygons.map(function(p) {
            p.flip();
        });
        return csg;
    }
}

// Construct a CSG solid from a list of `Polygon` instances.
CSG.fromPolygons=function(polygons) {
    var csg = new CSG();
    csg.polygons = polygons;
    return csg;
}

// # class Vector

// Represents a 3D vector.
// 
// Example usage:
// 
//     new CSG.Vector(1, 2, 3);
//     new CSG.Vector([1, 2, 3]);
//     new CSG.Vector({ x: 1, y: 2, z: 3 });

class Vector extends THREE.Vector3 {
    constructor(x, y, z) {
        if (arguments.length == 3)
            super(x, y, z)
        else if (Array.isArray(x))
            super(x[0], x[1], x[2])
        else if (typeof x == 'object')
            super().copy(x)
        else
            throw "Invalid constructor to vector"
    }

    clone() {
        return new Vector(this)
    }
    negated() {
        return this.clone().multiplyScalar(-1)
    }
    plus(a) {
        return this.clone().add(a);
    }
    minus(a) {
        return this.clone().sub(a)
    }
    times(a) {
        return this.clone().multiplyScalar(a)
    }
    dividedBy(a) {
        return this.clone().divideScalar(a)
    }
    lerp(a, t) {
        return this.plus(a.minus(this).times(t))
    }
    unit() {
        return this.dividedBy(this.length())
    }
    cross(a) {
        return THREE.Vector3.prototype.cross.call(this.clone(), a)
    }
}

// # class Vertex

// Represents a vertex of a polygon. Use your own vertex class instead of this
// one to provide additional features like texture coordinates and vertex
// colors. Custom vertex classes need to provide a `pos` property and `clone()`,
// `flip()`, and `interpolate()` methods that behave analogous to the ones
// defined by `CSG.Vertex`. This class provides `normal` so convenience
// functions like `CSG.sphere()` can return a smooth vertex normal, but `normal`
// is not used anywhere else.

class Vertex {

    constructor(pos, normal, uv) {
        this.pos = new Vector(pos);
        this.normal = new Vector(normal);
        this.uv = new Vector(uv);
    }

    clone() {
        return new Vertex(this.pos.clone(),this.normal.clone(),this.uv.clone());
    }

    // Invert all orientation-specific data (e.g. vertex normal). Called when the
    // orientation of a polygon is flipped.
    flip() {
        this.normal = this.normal.negated();
    }

    // Create a new vertex between this vertex and `other` by linearly
    // interpolating all properties using a parameter of `t`. Subclasses should
    // override this to interpolate additional properties.
    interpolate(other, t) {
        return new Vertex(this.pos.lerp(other.pos, t),this.normal.lerp(other.normal, t),this.uv.lerp(other.uv, t))
    }
}
;
// # class Plane

// Represents a plane in 3D space.

class Plane {
    constructor(normal, w) {
        this.normal = normal;
        this.w = w;
    }

    clone() {
        return new Plane(this.normal.clone(),this.w);
    }

    flip() {
        this.normal = this.normal.negated();
        this.w = -this.w;
    }

    // Split `polygon` by this plane if needed, then put the polygon or polygon
    // fragments in the appropriate lists. Coplanar polygons go into either
    // `coplanarFront` or `coplanarBack` depending on their orientation with
    // respect to this plane. Polygons in front or in back of this plane go into
    // either `front` or `back`.
    splitPolygon(polygon, coplanarFront, coplanarBack, front, back) {
        var COPLANAR = 0;
        var FRONT = 1;
        var BACK = 2;
        var SPANNING = 3;

        // Classify each point as well as the entire polygon into one of the above
        // four classes.
        var polygonType = 0;
        var types = [];
        for (var i = 0; i < polygon.vertices.length; i++) {
            var t = this.normal.dot(polygon.vertices[i].pos) - this.w;
            var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
            polygonType |= type;
            types.push(type);
        }

        // Put the polygon in the correct list, splitting it when necessary.
        switch (polygonType) {
        case COPLANAR:
            (this.normal.dot(polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
            break;
        case FRONT:
            front.push(polygon);
            break;
        case BACK:
            back.push(polygon);
            break;
        case SPANNING:
            var f = []
              , b = [];
            for (var i = 0; i < polygon.vertices.length; i++) {
                var j = (i + 1) % polygon.vertices.length;
                var ti = types[i]
                  , tj = types[j];
                var vi = polygon.vertices[i]
                  , vj = polygon.vertices[j];
                if (ti != BACK)
                    f.push(vi);
                if (ti != FRONT)
                    b.push(ti != BACK ? vi.clone() : vi);
                if ((ti | tj) == SPANNING) {
                    var t = (this.w - this.normal.dot(vi.pos)) / this.normal.dot(vj.pos.minus(vi.pos));
                    var v = vi.interpolate(vj, t);
                    f.push(v);
                    b.push(v.clone());
                }
            }
            if (f.length >= 3)
                front.push(new Polygon(f,polygon.shared));
            if (b.length >= 3)
                back.push(new Polygon(b,polygon.shared));
            break;
        }
    }

}

// `Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
// point is on the plane.
Plane.EPSILON = 1e-5;

Plane.fromPoints = function(a, b, c) {
    var n = b.minus(a).cross(c.minus(a)).unit();
    return new Plane(n,n.dot(a));
}


// # class Polygon

// Represents a convex polygon. The vertices used to initialize a polygon must
// be coplanar and form a convex loop. They do not have to be `Vertex`
// instances but they must behave similarly (duck typing can be used for
// customization).
// 
// Each convex polygon has a `shared` property, which is shared between all
// polygons that are clones of each other or were split from the same polygon.
// This can be used to define per-polygon properties (such as surface color).

class Polygon {

    constructor(vertices, shared) {
        this.vertices = vertices;
        this.shared = shared;
        this.plane = Plane.fromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
    }

    clone() {
        var vertices = this.vertices.map(function(v) {
            return v.clone();
        });
        return new Polygon(vertices,this.shared);
    }
    flip() {
        this.vertices.reverse().map(function(v) {
            v.flip();
        });
        this.plane.flip();
    }
}

// # class Node

// Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
// by picking a polygon to split along. That polygon (and all other coplanar
// polygons) are added directly to that node and the other polygons are added to
// the front and/or back subtrees. This is not a leafy BSP tree since there is
// no distinction between internal and leaf nodes.

class Node {
    constructor(polygons) {
        this.plane = null;
        this.front = null;
        this.back = null;
        this.polygons = [];
        if (polygons)
            this.build(polygons);
    }
    clone() {
        var node = new Node();
        node.plane = this.plane && this.plane.clone();
        node.front = this.front && this.front.clone();
        node.back = this.back && this.back.clone();
        node.polygons = this.polygons.map(function(p) {
            return p.clone();
        });
        return node;
    }

    // Convert solid space to empty space and empty space to solid space.
    invert() {
        for (var i = 0; i < this.polygons.length; i++)
            this.polygons[i].flip();
        
        this.plane.flip();
        if (this.front)
            this.front.invert();
        if (this.back)
            this.back.invert();
        var temp = this.front;
        this.front = this.back;
        this.back = temp;
    }

    // Recursively remove all polygons in `polygons` that are inside this BSP
    // tree.
    clipPolygons(polygons) {
        if (!this.plane)
            return polygons.slice();
        var front = []
          , back = [];
        for (var i = 0; i < polygons.length; i++) {
            this.plane.splitPolygon(polygons[i], front, back, front, back);
        }
        if (this.front)
            front = this.front.clipPolygons(front);
        if (this.back)
            back = this.back.clipPolygons(back);
        else
            back = [];
        return front.concat(back);
    }

    // Remove all polygons in this BSP tree that are inside the other BSP tree
    // `bsp`.
    clipTo(bsp) {
        this.polygons = bsp.clipPolygons(this.polygons);
        if (this.front)
            this.front.clipTo(bsp);
        if (this.back)
            this.back.clipTo(bsp);
    }

    // Return a list of all polygons in this BSP tree.
    allPolygons() {
        var polygons = this.polygons.slice();
        if (this.front)
            polygons = polygons.concat(this.front.allPolygons());
        if (this.back)
            polygons = polygons.concat(this.back.allPolygons());
        return polygons;
    }

    // Build a BSP tree out of `polygons`. When called on an existing tree, the
    // new polygons are filtered down to the bottom of the tree and become new
    // nodes there. Each set of polygons is partitioned using the first polygon
    // (no heuristic is used to pick a good split).
    build(polygons) {
        if (!polygons.length)
            return;
        if (!this.plane)
            this.plane = polygons[0].plane.clone();
        var front = []
          , back = [];
        for (var i = 0; i < polygons.length; i++) {
            this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
        }
        if (front.length) {
            if (!this.front)
                this.front = new Node();
            this.front.build(front);
        }
        if (back.length) {
            if (!this.back)
                this.back = new Node();
            this.back.build(back);
        }
    }
}

CSG.fromGeometry=function(geom){
    if(geom.isBufferGeometry)
        geom = new THREE.Geometry().fromBufferGeometry(geom)
    var fs = geom.faces;
    var vs = geom.vertices;
    var polys=[]
    var fm=['a','b','c']
    for(var i=0;i<fs.length;i++){
        var f = fs[i];
        var vertices=[]
        for(var j=0;j<3;j++) vertices.push(new Vertex(vs[f[fm[j]]],f.vertexNormals[j],geom.faceVertexUvs[0][i][j]))
        polys.push(new Polygon(vertices))
    }
    return CSG.fromPolygons(polys)
}
CSG._tmpm3 = new THREE.Matrix3();
CSG.fromMesh=function(mesh){

    var csg = CSG.fromGeometry(mesh.geometry)
    CSG._tmpm3.getNormalMatrix(mesh.matrix);
    for(var i=0;i<csg.polygons.length;i++){
        var p = csg.polygons[i]
        for(var j=0;j<p.vertices.length;j++){
            var v=p.vertices[j]
            v.pos.applyMatrix4(mesh.matrix);
            v.normal.applyMatrix3(CSG._tmpm3);
        }
    }
    return csg;
}

CSG.toMesh=function(csg,toMatrix){
    var geom = new THREE.Geometry();
    var ps = csg.polygons;
    var vs = geom.vertices;
    var fvuv = geom.faceVertexUvs[0]
    for(var i=0;i<ps.length;i++){
        var p = ps[i]
        var pvs=p.vertices;
        var v0=vs.length;
        var pvlen=pvs.length
        
        for(var j=0;j<pvlen;j++)
            vs.push(new THREE.Vector3().copy(pvs[j].pos))


        for(var j=3;j<=pvlen;j++){
            var fc = new THREE.Face3();
            var fuv = []
            fvuv.push(fuv)
            var fnml = fc.vertexNormals;
            fc.a=v0;
            fc.b=v0+j-2;
            fc.c=v0+j-1;

            fnml.push(new THREE.Vector3().copy(pvs[0].normal))
            fnml.push(new THREE.Vector3().copy(pvs[j-2].normal))
            fnml.push(new THREE.Vector3().copy(pvs[j-1].normal))
            fuv.push(new THREE.Vector3().copy(pvs[0].uv))
            fuv.push(new THREE.Vector3().copy(pvs[j-2].uv))
            fuv.push(new THREE.Vector3().copy(pvs[j-1].uv))

            fc.normal = new THREE.Vector3().copy(p.plane.normal)
            geom.faces.push(fc)
        }
    }
    var inv = new THREE.Matrix4().getInverse(toMatrix);
    geom.applyMatrix(inv);
    geom.verticesNeedUpdate = geom.elementsNeedUpdate = geom.normalsNeedUpdate = true;
    geom.computeBoundingSphere();
    geom.computeBoundingBox();
    var m = new THREE.Mesh(geom);
    m.matrix.copy(toMatrix);
    m.matrix.decompose(m.position,m.rotation,m.scale)
    m.updateMatrixWorld();
    return m
}


CSG.ieval=function(tokens,index=0){
    if(typeof tokens === 'string')
        CSG.currentOp=tokens;
    else if(tokens instanceof Array){
        for(let i=0;i<tokens.length;i++)CSG.ieval(tokens[i],0);
    }else if(typeof tokens==='object'){
        var op=CSG.currentOp;
        tokens.updateMatrix();
        tokens.updateMatrixWorld();
        if(!CSG.sourceMesh)
            CSG.currentPrim =  CSG.fromMesh(CSG.sourceMesh = tokens);
        else{
            CSG.nextPrim = CSG.fromMesh(tokens);
            CSG.currentPrim = CSG.currentPrim[op](CSG.nextPrim);
        }
        if(CSG.doRemove)tokens.parent.remove(tokens);
    }//union,subtract,intersect,inverse
}

CSG.eval=function(tokens,doRemove){//[['add',mesh,mesh,mesh,mesh],['sub',mesh,mesh,mesh,mesh]]
    CSG.currentOp=null;
    CSG.sourceMesh=null;
    CSG.doRemove=doRemove;
    CSG.ieval(tokens)
    var result = CSG.toMesh( CSG.currentPrim, CSG.sourceMesh.matrix );
    result.material = CSG.sourceMesh.material;
    result.castShadow  = result.receiveShadow = true;
    return result;
}

// Return a new CSG solid representing space in either this solid or in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
// 
//     A.union(B)
// 
//     +-------+            +-------+
//     |       |            |       |
//     |   A   |            |       |
//     |    +--+----+   =   |       +----+
//     +----+--+    |       +----+       |
//          |   B   |            |       |
//          |       |            |       |
//          +-------+            +-------+
// 
// Return a new CSG solid representing space in this solid but not in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
// 
//     A.subtract(B)
// 
//     +-------+            +-------+
//     |       |            |       |
//     |   A   |            |       |
//     |    +--+----+   =   |    +--+
//     +----+--+    |       +----+
//          |   B   |
//          |       |
//          +-------+
// 
// Return a new CSG solid representing space both this solid and in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
// 
//     A.intersect(B)
// 
//     +-------+
//     |       |
//     |   A   |
//     |    +--+----+   =   +--+
//     +----+--+    |       +--+
//          |   B   |
//          |       |
//          +-------+
//
    </script>
    <script>
        window.addEventListener("DOMContentLoaded",app);

function app() {
	var header = document.querySelector("header"),
		difSelect = document.querySelector(".difficulty-select"),
		difButtons = difSelect.querySelectorAll("button"),
		tutorialBox = document.querySelector(".tutorial"),
		replayButton = document.querySelector(".replay"),

		scene,
		camera,
		renderer,
		hemiLight,
		pointLight,
		touch = {hold: false, x: 0},

		difSelectActive = false,
		scoreCounterActive = false,
		replayBtnActive = false,

		game = null,
		randomInt = (min,max) => Math.round(Math.random() * (max - min)) + min,
		skyColor = 0x69c6d0,
		pointLightZ = -60,
		cameraY = 45,
		cameraYMin = 7,
		renderDistance = 8,
		roadChunks = [];

	class Game {
		constructor(args) {
			// 0: easy, 1: medium (default), 2: hard, 3: brutal
			let d = args.difficulty;
			this.difficulty = d >= 0 && d <= 3 ? d : 1;

			this.tutorial = args.tutorial === true;
			this.over = false;
			this.preparingNew = false;
			this.score = 0;
			this.noScoreXZone = 15;
			this.vehicles = [
				new Vehicle({
					color: 0xff1717,
					x: 0,
					z: 0,
					modelID: 0,
					speed: 1,
					acceleration: 0.001 * 2**d,
					name: "Vehicle 0"
				})
			];
			this.vehicleSpawns = this.vehicles.length;
			this.vehicleLimit = 9;
			this.vehicleIDCtrld = 0;
			this.spark = null;
		}
	}
	class RoadChunk {
		constructor(zSpaces) {
			let chunkSize = 40,
				lineWidth = 1,
				lineHeight = 4,
				dotLines = 3;

			this.chunkSize = chunkSize;
			// surface
			this.surfaceGeo = new THREE.PlaneBufferGeometry(chunkSize,chunkSize);
			this.surfaceMat = new THREE.MeshLambertMaterial({
				color: 0x575757
			});
			this.surface = new THREE.Mesh(this.surfaceGeo,this.surfaceMat);
			this.surface.name = "Road Chunk";
			this.surface.rotation.x = -Math.PI/2;
			this.surface.position.set(0,0,zSpaces*chunkSize);
			this.surface.receiveShadow = true;
			scene.add(this.surface);

			// shoulder lines
			let lineGeo = new THREE.PlaneBufferGeometry(lineWidth,chunkSize),
				lineMat = new THREE.MeshLambertMaterial({
					color: 0xffffff
				}),
				line = new THREE.Mesh(lineGeo,lineMat);
			line.receiveShadow = true;

			let leftShoulder = line.clone();
			leftShoulder.position.set(-chunkSize*0.375,0,0.01);
			this.surface.add(leftShoulder);

			let rightShoulder = line.clone();
			rightShoulder.position.set(chunkSize*0.375,0,0.01);
			this.surface.add(rightShoulder);

			// dotted lines
			let dotLineGeo = new THREE.PlaneBufferGeometry(lineWidth,lineHeight),
				dotLineMat = new THREE.MeshLambertMaterial({
					color: 0xffffff
				}),
				dotLine = new THREE.Mesh(dotLineGeo,dotLineMat);

			for (let l = 0; l < dotLines; ++l) {
				let y = chunkSize/2 - (chunkSize / dotLines) * l - lineHeight/2;

				let leftLine = dotLine.clone();
				leftLine.position.set(-chunkSize*0.125,y,0.01);
				this.surface.add(leftLine);

				let rightLine = dotLine.clone();
				rightLine.position.set(chunkSize*0.125,y,0.01);
				this.surface.add(rightLine);
			}
		}
	}
	class Vehicle {
		constructor(args) {
			this.color = args.color || randomInt(0x171717,0xcccccc);
			this.x = args.x || 0;
			this.z = args.z || 0;
			this.width = 1;
			this.height = 1;
			this.depth = 1;
			this.speed = args.speed || 1;
			this.acceleration = args.acceleration || 0;
			this.model = null;
			this.name = args.name || "";

			this.maxSpeed = 4;
			this.isSteering = false;
			this.steerAngle = 0;
			this.maxSteerAngle = 30;
			this.steerSpeed = 0.15;
			this.steerDir = "";
			this.xLimit = 20;
			this.crashed = false;
			this.deceleration = 0.01;

			// 0: car, 1: truck, 2: tractor trailer
			let modelID = args.modelID;

			if (modelID === undefined)
				modelID = Math.round(Math.random() * 2)

			// dimensions refer to hitbox
			switch (modelID) {
				case 1:
					this.width = 5;
					this.height = 5;
					this.depth = 10;
					this.model = new Truck(this.color,this.x,this.z,this.name); 
					break;
				case 2:
					this.width = 5;
					this.height = 8;
					this.depth = 18;
					this.model = new TractorTrailer(this.color,this.x,this.z,this.name);
					break;
				default:
					this.width = 5;
					this.height = 4;
					this.depth = 10;
					this.model = new Car(this.color,this.x,this.z,this.name);
					break;
			}
		}
		accelerate() {
			if (this.speed < .........完整代码请登录后点击上方下载按钮下载查看

网友评论0