three打造一个控制赛车不相撞的游戏代码

代码语言:html

所属分类:游戏

代码描述:three打造一个控制赛车不相撞的游戏代码,按住键盘向上箭头开始,向下箭头减速,R键重新开始

代码标签: 控制 赛车 相撞 游戏

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

<html lang="en">
<head>

    <meta charset="UTF-8">





    <style>
@import url("https://fonts.googleapis.com/css?family=Press+Start+2P");

        body {
            margin: 0;
            color: white;
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        }

        button {
            outline: none;
            cursor: pointer;
            border: none;
            box-shadow: 3px 5px 0px 0px rgba(0, 0, 0, 0.75);
        }

        a,
        a:visited {
            color: inherit;
        }

        #score {
            position: absolute;
            font-family: "Press Start 2P", cursive;
            font-size: 0.9em;
            color: white;
            transform: translate(-50%, -50%);
            opacity: 0.9;
            max-width: 100px;
            text-align: center;
            line-height: 1.6em;
        }

        #controls {
            position: absolute;
            bottom: 50px;
            left: 50px;
            display: none;
        }

        #controls #buttons {
            width: 80px;
            opacity: 0;
            transition: opacity 2s;
        }

        #controls #instructions {
            margin-left: 20px;
            max-width: 300px;
            background-color: rgba(0, 0, 0, 0.2);
            padding: 20px;
            opacity: 0;
            transition: opacity 2s;
        }

        #controls button {
            width: 100%;
            height: 40px;
            background-color: white;
            border: 1px solid black;
            margin-bottom: 10px;
        }

        #results {
            position: absolute;
            align-items: center;
            justify-content: center;
            height: 100%;
            width: 100%;
            background-color: rgba(20, 20, 20, 0.75);
            display: none;
            z-index: 51;
        }

        #results .content {
            max-width: 350px;
            padding: 50px;
            border-radius: 20px;
        }

        #result-youtube {
            display: flex;
            background-color: white;
            padding: 20px;
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        #result-youtube span {
            margin-top: 5px;
            margin-left: 20px;
        }

        .youtube,
        #youtube-card {
            display: none;
            color: black;
        }

        #youtube-main {
            opacity: 0;
            transition: opacity 2s;
        }

@media (min-height: 425px) {
            #score {
                font-size: 1.5em;
                max-width: 150px;
            }

            #controls {
                display: flex;
            }

    </style>



</head>

<body >
    <div id="score" style="left: 212.711px; top: 329.5px;">
        Press UP
    </div>

    <div id="controls">
        <div id="buttons" style="opacity: 1;">
            <button id="accelerate">
                <svg width="30" height="30" viewBox="0 0 10 10">
                    <g transform="rotate(0, 5,5)">
                        <path d="M5,4 L7,6 L3,6 L5,4"></path>
                    </g>
                </svg>
            </button>
            <button id="decelerate">
                <svg width="30" height="30" viewBox="0 0 10 10">
                    <g transform="rotate(180, 5,5)">
                        <path d="M5,4 L7,6 L3,6 L5,4"></path>
                    </g>
                </svg>
            </button>
        </div>
        <div id="instructions" style="opacity: 1;">
            Press UP to start. Avoid collision with other vehicles by accelerating
            or decelerating with the UP and DOWN keys.
        </div>
    </div>

    <div id="results" style="display: none;">
        <div class="content">
            <h1>You hit another vehicle</h1>
            <p>
                To reset the game press R
            </p>

   
        
        </div>
    </div>

    <a id="youtube-main" class="youtube" target="_blank" style="opacity: 1;">
      
    </a>
 
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/three.126.js"></script>
    <script>
        /*

Three.js video tutorial explaining the source code

Youtube: https://youtu.be/JhgBwJn1bQw

In the tutorial, we go through the source code of this game. We cover, how to set up a Three.js scene with box objects, how to add lights, how to set up the camera, how to add animation and event handlers. We also add textures with HTML Canvas and learn how to draw 2D shapes in Three.js then how to turn them into extruded geometries.

Comparing to the tutorial this version has some extra features:
- trucks also pop up on the other track
- the extruded geometry also has a texture
- there are trees around the track
- shadows
- the game reacts to window resizing

Check out my YouTube channel for other game tutorials: https://www.youtube.com/channel/UCxhgW0Q5XLvIoXHAfQXg9oQ

*/

        window.focus(); // Capture keys right away (by default focus is on editor)

        // Pick a random value from an array
        function pickRandom(array) {
            return array[Math.floor(Math.random() * array.length)];
        }

        // The Pythagorean theorem says that the distance between two points is
        // the square root of the sum of the horizontal and vertical distance's square
        function getDistance(coordinate1, coordinate2) {
            const horizontalDistance = coordinate2.x - coordinate1.x;
            const verticalDistance = coordinate2.y - coordinate1.y;
            return Math.sqrt(horizontalDistance ** 2 + verticalDistance ** 2);
        }

        const vehicleColors = [
            0xa52523,
            0xef2d56,
            0x0ad3ff,
            0xff9f1c /*0xa52523, 0xbdb638, 0x78b14b*/];


        const lawnGreen = "#67C240";
        const trackColor = "#546E90";
        const edgeColor = "#725F48";
        const treeCrownColor = 0x498c2c;
        const treeTrunkColor = 0x4b3f2f;

        const wheelGeometry = new THREE.BoxBufferGeometry(12, 33, 12);
        const wheelMaterial = new THREE.MeshLambertMaterial({
            color: 0x333333
        });
        const treeTrunkGeometry = new THREE.BoxBufferGeometry(15, 15, 30);
        const treeTrunkMaterial = new THREE.MeshLambertMaterial({
            color: treeTrunkColor
        });

        const treeCrownMaterial = new THREE.MeshLambertMaterial({
            color: treeCrownColor
        });


        const config = {
            showHitZones: false,
            shadows: true,
            // Use shadow
            trees: true,
            // Add trees to the map
            curbs: true,
            // Show texture on the extruded geometry
            grid: false // Show grid helper
        };

        let score;
        const speed = 0.0017;

        const playerAngleInitial = Math.PI;
        let playerAngleMoved;
        let accelerate = false; // Is the player accelerating
        let decelerate = false; // Is the player decelerating

        let otherVehicles = [];
        let ready;
        let lastTimestamp;

        const trackRadius = 225;
        const trackWidth = 45;
        const innerTrackRadius = trackRadius - trackWidth;
        const outerTrackRadius = trackRadius + trackWidth;

        const arcAngle1 = 1 / 3 * Math.PI; // 60 degrees

        const deltaY = Math.sin(arcAngle1) * innerTrackRadius;
        const arcAngle2 = Math.asin(deltaY / outerTrackRadius);

        const arcCenterX =
        (Math.cos(arcAngle1) * innerTrackRadius +
            Math.cos(arcAngle2) * outerTrackRadius) /
        2;

        const arcAngle3 = Math.acos(arcCenterX / innerTrackRadius);

        const arcAngle4 = Math.acos(arcCenterX / outerTrackRadius);

        const scoreElement = document.getElementById("score");
        const buttonsElement = document.getElementById("buttons");
        const instructionsElement = document.getElementById("instructions");
        const resultsElement = document.getElementById("results");
        const accelerateButton = document.getElementById("accelerate");
        const decelerateButton = document.getElementById("decelerate");
        const youtubeLogo = document.getElementById("youtube-main");

        setTimeout(() => {
            if (ready) instructionsElement.style.opacity = 1;
            buttonsElement.style.opacity = 1;
            youtubeLogo.style.opacity = 1;
        }, 4000);

        // Initialize ThreeJs
        // Set up camera
        const aspectRatio = window.innerWidth / window.innerHeight;
        const cameraWidth = 960;
        const cameraHeight = cameraWidth / aspectRatio;

        const camera = new THREE.OrthographicCamera(
            cameraWidth / -2, // left
            cameraWidth / 2, // right
            cameraHeight / 2, // top
            cameraHeight / -2, // bottom
            50, // near plane
            700 // far plane
        );

        camera.position.set(0, -210, 300);
        camera.lookAt(0, 0, 0);

        const scene = new THREE.Scene();

        const playerCar = Car();
        scene.add(playerCar);

        renderMap(cameraWidth, cameraHeight * 2); // The map height is higher because we look at the map from an angle

        // Set up lights
        const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
        scene.add(ambientLight);

        const dirLight = new THREE.DirectionalLight(0xffffff, 0.6);
        dirLight.position.set(100, -300, 300);
        dirLight.castShadow = true;
        dirLight.shadow.mapSize.width = 1024;
        dirLight.shadow.mapSize.height = 1024;
        dirLight.shadow.camera.left = -400;
        dirLight.shadow.camera.right = 350;
        dirLight.shadow.camera.top = 400;
        dirLight.shadow.camera.bottom = -300;
        dirLight.shadow.camera.near = 100;
        dirLight.shadow.camera.far = 800;
        scene.add(dirLight);

        // const cameraHelper = new THREE.CameraHelper(dirLight.shadow.camera);
        // scene.add(cameraHelper);

        if (config.grid) {
            const gridHelper = new THREE.GridHelper(80, 8);
            gridHelper.rotation.x = Math.PI / 2;
            scene.add(gridHelper);
        }

        // Set up renderer
        const renderer = new THREE.WebGLRenderer({
            antialias: true,
            powerPreference: "high-performance"
        });

        renderer.setSize(window.innerWidth, window.innerHeight);
        if (config.shadows) renderer.shadowMap.enabled = true;
        document.body.appendChild(renderer.domElement);

        reset();

        function reset() {
            // Reset position and score
            playerAngleMoved = 0;
            score = 0;
            scoreElement.innerText = "Press UP";

            // Remove other vehicles
            otherVehicles.forEach(vehicle => {
                // Remove the vehicle from the scene
                scene.remove(vehicle.mesh);

                // If it has hit-zone helpers then remove them as well
                if (vehicle.mesh.userData.hitZone1)
                    scene.remove(vehicle.mesh.userData.hitZone1);
                if (vehicle.mesh.userData.hitZone2)
                    scene.remove(vehicle.mesh.userData.hitZone2);
                if (vehicle.mesh.userData.hitZone3)
                    scene.remove(vehicle.mesh.userData.hitZone3);
            });
            otherVehicles = [];

            resultsElement.style.display = "none";

            lastTimestamp = undefined;

            // Place the player's car to the starting position
            movePlayerCar(0);

            // Render the scene
            renderer.render(scene,
                camera);

            ready = true;
        }

        function startGame() {
            if (ready) {
                ready = false;
                scoreElement.innerText = 0;
                buttonsElement.style.opacity = 1;
                instructionsElement.style.opacity = 0;
                youtubeLogo.style.opacity = 1;
                renderer.setAnimationLoop(animation);
            }
        }

        function positionScoreElement() {
            const arcCenterXinPixels = arcCenterX / cameraWidth * window.innerWidth;
            scoreElement.style.cssText = `
            left: ${window.innerWidth / 2 - arcCenterXinPixels * 1.3}px;
            top: ${window.innerHeight / 2}px
            `;
        }

        function getLineMarkings(mapWidth, mapHeight) {
            const canvas = document.createElement("canvas");
            canvas.width = mapWidth;
            canvas.height = mapHeight;
            const context = canvas.getContext("2d");

            context.fillStyle = trackColor;
            context.fillRect(0, 0, mapWidth, mapHeight);

            context.lineWidth = 2;
            context.strokeStyle = "#E0FFFF";
            context.setLineDash([10, 14]);

            // Left circle
            context.beginPath();
            context.arc(
                mapWidth / 2 - arcCenterX,
                mapHeight / 2,
                trackRadius,
                0,
                Math.PI * 2);

            context.stroke();

            // Right circle
            context.beginPath();
            context.arc(
                mapWidth / 2 + arcCenterX,
                mapHeight / 2,
                trackRadius,
                0,
                Math.PI * 2);

            context.stroke();

            return new THREE.CanvasTexture(canvas);
        }

        function getCurbsTexture(mapWidth, mapHeight) {
            const canvas = document.createElement("canvas");
            canvas.width = mapWidth;
            canvas.height = mapHeight;
            const context = canvas.getContext("2d");

            context.fillStyle = lawnGreen;
            context.fillRect(0, 0, mapWidth, mapHeight);

            // Extra big
            context.lineWidth = 65;
            context.strokeStyle = "#A2FF75";
            context.beginPath();
            context.arc(
                mapWidth / 2 - arcCenterX,
                mapHeight / 2,
                innerTrackRadius,
                arcAngle1,
                -arcAngle1);

            context.arc(
                mapWidth / 2 + arcCenterX,
                mapHeight / 2,
                outerTrackRadius,
                Math.PI + arcAngle2,
                Math.PI - arcAngle2,
                true);

            context.stroke();

            context.beginPath();
            context.arc(
                mapWidth / 2 + arcCenterX,
                mapHeight / 2,
                innerTrackRadius,
                Math.PI + arcAngle1,
                Math.PI - arcAngle1);

            context.arc(
                mapWidth / 2 - arcCenterX,
                mapHeight / 2,
                outerTrackRadius,
                arcAngle2,
                -arcAngle2,
                true);

            context.stroke();

            // Extra small
            context.lineWidth = 60;
            context.strokeStyle = lawnGreen;
            context.beginPath();
            context.arc(
                mapWidth / 2 - arcCenterX,
                mapHeight / 2,
                innerTrackRadius,
                arcAngle1,
                -arcAngle1);

            context.arc(
                mapWidth / 2 + arcCenterX,
                mapHeight / 2,
                outerTrackRadius,
                Math.PI + arcAngle2,
                Math.PI - arcAngle2,
                true);

            context.arc(
                mapWidth / 2 + arcCenterX,
                mapHeight / 2,
                innerTrackRadius,
                Math.PI + arcAngle1,
                Math.PI - arcAngle1);

            context.arc(
                mapWidth / 2 - arcCenterX,
                mapHeight / 2,
                outerTrackRadius,
                arcAngle2,
                -arcAngle2,
                true);

            context.stroke();

            // Base
            context.lineWidth = 6;
            context.strokeStyle = edgeColor;

            // Outer circle left
            context.beginPath();
            context.arc(
                mapWidth / 2 - arcCenterX,
                mapHeight / 2,
                outerTrackRadius,
                0,
                Math.PI * 2);

            context.stroke();

            // Outer circle right
            context.beginPath();
            context.arc(
                mapWidth / 2 + arcCenterX,
                mapHeight / 2,
                outerTrackRadius,
                0,
                Math.PI * 2);

            context.stroke();

            // Inner circle left
            context.beginPath();
            context.arc(
                mapWidth / 2 - arcCenterX,
                mapHeight / 2,
                innerTrackRadius,
                0,
                Math.PI * 2);

            context.stroke();

            // Inner circle right
            context.beginPath();
            context.arc(
                mapWidth / 2 + arcCenterX,
                mapHeight / 2,
                innerTrackRadius,
                0,
                Math.PI * 2);

            context.stroke();

            return new THREE.CanvasTexture(canvas);
        }

        function getLeftIsland() {
            const islandLeft = new THREE.Shape();

            islandLeft.absarc(
                -arcCenterX,
                0,
                innerTrackRadius,
                arcAngle1,
                -arcAngle1,
                false);


            islandLeft.absarc(
                arcCenterX,
                0,
                outerTrackRadius,
                Math.PI + arcAngle2,
                Math.PI - arcAngle2,
                true);


            return islandLeft;
        }

        function getMiddleIsland() {
            const islandMiddle = new THREE.Shape();

            islandMiddle.absarc(
                -arcCenterX,
                0,
                innerTrackRadius,
                arcAngle3,
                -arcAngle3,
                true);


            islandMiddle.absarc(
                arcCenterX,
                0,
                innerTrackRadius,
                Math.PI + arcAngle3,
                Math.PI - arcAngle3,
                true);


            return islandMiddle;
        }

        function getRightIsland() {
            const islandRight = new THREE.Shape();

            islandRight.absarc(
                arcCenterX,
                0,
                innerTrackRadius,
                Math.PI - arcAngle1,
                Math.PI + arcAngle1,
                true);


            islandRight.absarc(
                -arcCenterX,
                0,
                outerTrackRadius,
                -arcAngle2,
                arcAngle2,
                false);


            return islandRight;
        }

        function getOuterField(mapWidth, mapHeight) {
            const field = new THREE.Shape();

            field.moveTo(-mapWidth / 2, -mapHeight / 2);
            field.lineTo(0, -mapHeight / 2);

            field.absarc(-arcCenterX, 0, outerTrackRadius, -arcAngle4, arcAngle4, true);

            field.absarc(
                arcCenterX,
                0,
                outerTrackRadius,
                Math.PI - arcAngle4,
                Math.PI + arcAngle4,
                true);


            field.lineTo(0, -mapHeight / 2);
            field.lineTo(mapWidth / 2, -mapHeight / 2);
            field.lineTo(mapWidth / 2, mapHeight / 2);
            field.lineTo(-mapWidth / 2, mapHeight / 2);

            return field;
        }

        function renderMap(mapWidth, mapHeight) {
            const lineMarkingsTexture = getLineMarkings(mapWidth, mapHeight);

            const planeGeometry = new THREE.PlaneBufferGeometry(mapWidth, mapHeight);
            const planeMaterial = new THREE.MeshLambertMaterial({
                map: lineMarkingsTexture
            });

            const plane = new THREE.Mesh(planeGeometry, planeMaterial);
            plane.receiveShadow = true;
            plane.matrixAutoUpdate = false;
            scene.add(plane);

            // Extruded geometry with curbs
            const islandLeft = getLeftIsland();
            const islandMiddle = getMiddleIsland();
            const islandRight = getRightIsland();
            const outerField = getOuterField(mapWidth, mapHeight);

            // Mapping a texture on an extruded geometry works differently than mapping it to a box
            // By default it is mapped to a 1x1 unit square, and we have to stretch it out by setting repeat
            // We also need to shift it by setting the offset to have it centered
            const curbsTexture = getCurbsTexture(mapWidth, mapHeight);
            curbsTexture.offset = new THREE.Vector2(0.5, 0.5);
            curbsTexture.repeat.set(1 / mapWidth, 1 / mapHeight);

            // An extruded geometry turns a 2D shape into 3D by giving it a depth
            const fieldGeometry = new THREE.ExtrudeBufferGeometry(
                [islandLeft, islandRight.........完整代码请登录后点击上方下载按钮下载查看

网友评论0