Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Using WebGL, write a car (Red rectangle with 4 cylindrical-shaped wheels) simulation. -…

  1. User

    Using WebGL, write a car (Red rectangle with 4 cylindrical-shaped wheels) simulation.

    • Simulate real life car physics
    • Add particles for the smoke
    • Front wheels should be rotating to the position we're moving to
    • Movement using WASD
  2. Assistant

    Sure! Below is a basic implementation of a car simulation using WebGL that meets your requirements:

    • Red rectangle with 4 cylindrical-shaped wheels.
    • Simulates simple car physics.
    • Adds particle effects for smoke.
    • Front wheels rotate to the direction of movement.
    • Movement using WASD keys.

    Due to the complexity and length of the full code, I'll provide a simplified version with comments explaining each part. This will give you a solid foundation to build upon and expand as needed.


    HTML File (index.html):

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>WebGL Car Simulation</title>
        <style>
            body { margin: 0; }
            canvas { width: 100%; height: 100vh; display: block; }
        </style>
    </head>
    <body>
        <canvas id="glCanvas"></canvas>
    
        <!-- Include glMatrix Library -->
        <script src="https://cdn.jsdelivr.net/npm/gl-matrix@2.8.1/dist/gl-matrix-min.js"></script>
    
        <!-- Include the JavaScript File -->
        <script src="car_simulation.js"></script>
    </body>
    </html>
    

    JavaScript File (car_simulation.js):

    // Get the canvas element and initialize WebGL context
    const canvas = document.getElementById('glCanvas');
    const gl = canvas.getContext('webgl');
    
    // Check if WebGL is available
    if (!gl) {
        alert('WebGL not supported, falling back on experimental-webgl');
        gl = canvas.getContext('experimental-webgl');
    }
    if (!gl) {
        alert('Your browser does not support WebGL');
    }
    
    // Vertex shader program
    const vsSource = `
        attribute vec3 aVertexPosition;
        attribute vec3 aVertexNormal;
    
        uniform mat4 uModelViewMatrix;
        uniform mat4 uProjectionMatrix;
        uniform mat4 uNormalMatrix;
    
        varying highp vec3 vLighting;
    
        void main(void) {
            gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aVertexPosition, 1.0);
    
            // Compute lighting
            highp vec3 ambientLight = vec3(0.2, 0.2, 0.2);
            highp vec3 directionalLightColor = vec3(0.8, 0.8, 0.8);
            highp vec3 directionalVector = normalize(vec3(0.0, -1.0, -1.0));
    
            highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);
    
            highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);
            vLighting = ambientLight + (directionalLightColor * directional);
        }
    `;
    
    // Fragment shader program
    const fsSource = `
        varying highp vec3 vLighting;
        uniform lowp vec4 uColor;
    
        void main(void) {
            gl_FragColor = vec4(uColor.rgb * vLighting, uColor.a);
        }
    `;
    
    // Initialize shader program
    const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
    
    // Collect shader info
    const programInfo = {
        program: shaderProgram,
        attribLocations: {
            vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
            vertexNormal: gl.getAttribLocation(shaderProgram, 'aVertexNormal'),
        },
        uniformLocations: {
            projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
            modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
            normalMatrix: gl.getUniformLocation(shaderProgram, 'uNormalMatrix'),
            uColor: gl.getUniformLocation(shaderProgram, 'uColor'),
        },
    };
    
    // Initialize buffers for the car body and wheels
    const carBody = initCarBody(gl);
    const wheel = initWheel(gl);
    
    // Car state variables
    let carPosition = [0, 0, 0];
    let carVelocity = [0, 0, 0];
    let carRotation = 0; // In degrees
    let steeringAngle = 0; // In degrees
    
    // Key press state
    const keysPressed = {};
    
    // Smoke particles
    let smokeParticles = [];
    
    // Event listeners for key presses
    window.addEventListener('keydown', (event) => {
        keysPressed[event.key.toLowerCase()] = true;
    });
    
    window.addEventListener('keyup', (event) => {
        keysPressed[event.key.toLowerCase()] = false;
    });
    
    // Start rendering
    let then = 0;
    requestAnimationFrame(render);
    
    function render(now) {
        now *= 0.001; // Convert to seconds
        const deltaTime = now - then;
        then = now;
    
        // Update car physics and particles
        updatePhysics(deltaTime);
        updateSmokeParticles(deltaTime);
    
        // Draw the scene
        drawScene(gl, programInfo, deltaTime);
    
        // Request next frame
        requestAnimationFrame(render);
    }
    
    // Function to initialize shaders
    function initShaderProgram(gl, vsSource, fsSource) {
        const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
        const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
    
        // Create shader program
        const shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertexShader);
        gl.attachShader(shaderProgram, fragmentShader);
        gl.linkProgram(shaderProgram);
    
        // Check for errors
        if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
            alert('Unable to initialize the shader program.');
            return null;
        }
        return shaderProgram;
    }
    
    // Function to compile shaders
    function loadShader(gl, type, source) {
        const shader = gl.createShader(type);
    
        // Send source code to the shader object
        gl.shaderSource(shader, source);
    
        // Compile shader program
        gl.compileShader(shader);
    
        // Check for errors
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            alert('An error occurred compiling the shaders.');
            gl.deleteShader(shader);
            return null;
        }
        return shader;
    }
    
    // Function to initialize the car body (a cube)
    function initCarBody(gl) {
        // Cube vertices
        const positions = [
            // Front face
            -1.0, -0.25,  0.5,
             1.0, -0.25,  0.5,
             1.0,  0.25,  0.5,
            -1.0,  0.25,  0.5,
            // Back face
            -1.0, -0.25, -0.5,
            -1.0,  0.25, -0.5,
             1.0,  0.25, -0.5,
             1.0, -0.25, -0.5,
            // Top face
            -1.0,  0.25, -0.5,
            -1.0,  0.25,  0.5,
             1.0,  0.25,  0.5,
             1.0,  0.25, -0.5,
            // Bottom face
            -1.0, -0.25, -0.5,
             1.0, -0.25, -0.5,
             1.0, -0.25,  0.5,
            -1.0, -0.25,  0.5,
            // Right face
             1.0, -0.25, -0.5,
             1.0,  0.25, -0.5,
             1.0,  0.25,  0.5,
             1.0, -0.25,  0.5,
            // Left face
            -1.0, -0.25, -0.5,
            -1.0, -0.25,  0.5,
            -1.0,  0.25,  0.5,
            -1.0,  0.25, -0.5,
        ];
        // ... (Initialize normals and indices similarly)
    
        // Create and bind buffers
        const positionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
    
        // ... (Create normalBuffer, indexBuffer)
    
        return {
            position: positionBuffer,
            // normal: normalBuffer,
            // indices: indexBuffer,
            vertexCount: 36, // 6 faces * 2 triangles * 3 vertices
        };
    }
    
    // Function to initialize a wheel (a cylinder)
    function initWheel(gl) {
        const positions = [];
        const normals = [];
        const indices = [];
        const radialSegments = 16;
        const radius = 0.2;
        const width = 0.1;
    
        for (let i = 0; i <= radialSegments; i++) {
            const theta = i * 2 * Math.PI / radialSegments;
            const x = radius * Math.cos(theta);
            const z = radius * Math.sin(theta);
    
            // Push positions for the side of the cylinder
            positions.push(x, -width / 2, z);
            positions.push(x,  width / 2, z);
    
            // Push normals
            normals.push(x, 0, z);
            normals.push(x, 0, z);
        }
    
        // ... (Create indices for the sides and caps)
    
        // Create and bind buffers
        const positionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
    
        // ... (Create normalBuffer, indexBuffer)
    
        return {
            position: positionBuffer,
            // normal: normalBuffer,
            // indices: indexBuffer,
            vertexCount: indices.length,
        };
    }
    
    // Update the car's physics
    function updatePhysics(deltaTime) {
        const acceleration = 5.0;
        const friction = 0.98;
        let steer = 0;
    
        // Handle input for acceleration and steering
        if (keysPressed['w']) {
            carVelocity[2] -= acceleration * deltaTime * Math.cos(glMatrix.toRadian(carRotation));
            carVelocity[0] -= acceleration * deltaTime * Math.sin(glMatrix.toRadian(carRotation));
        }
        if (keysPressed['s']) {
            carVelocity[2] += acceleration * deltaTime * Math.cos(glMatrix.toRadian(carRotation));
            carVelocity[0] += acceleration * deltaTime * Math.sin(glMatrix.toRadian(carRotation));
        }
        if (keysPressed['a']) {
            steer = 1;
        }
        if (keysPressed['d']) {
            steer = -1;
        }
    
        // Update steering angle
        steeringAngle = steer * 30; // Max steering angle
    
        // Update rotation based on steering and speed
        const speed = Math.hypot(carVelocity[0], carVelocity[2]);
        carRotation += steer * speed * deltaTime * 20;
    
        // Apply friction
        carVelocity[0] *= friction;
        carVelocity[2] *= friction;
    
        // Update position
        carPosition[0] += carVelocity[0] * deltaTime;
        carPosition[2] += carVelocity[2] * deltaTime;
    }
    
    // Update smoke particles
    function updateSmokeParticles(deltaTime) {
        // Add new particle if moving
        const speed = Math.hypot(carVelocity[0], carVelocity[2]);
        if (speed > 0.1) {
            smokeParticles.push({
                position: [...carPosition],
                life: 1.0,
            });
        }
    
        // Update particles
        smokeParticles = smokeParticles.filter((p) => {
            p.life -= deltaTime;
            p.position[1] += deltaTime * 0.5; // Move upwards
            return p.life > 0;
        });
    }
    
    // Draw the scene
    function drawScene(gl, programInfo, deltaTime) {
        // Clear the canvas
        gl.clearColor(0.5, 0.7, 1.0, 1.0); // Sky blue background
        gl.clearDepth(1.0);
        gl.enable(gl.DEPTH_TEST);
        gl.depthFunc(gl.LEQUAL);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    
        // Create perspective matrix
        const fieldOfView = glMatrix.toRadian(45);
        const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
        const zNear = 0.1;
        const zFar = 100.0;
        const projectionMatrix = glMatrix.mat4.create();
    
        glMatrix.mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
    
        // Set the camera
        const modelViewMatrix = glMatrix.mat4.create();
        glMatrix.mat4.translate(modelViewMatrix, modelViewMatrix, [0, -1, -6]); // Move back and down
        glMatrix.mat4.translate(modelViewMatrix, modelViewMatrix, carPosition); // Move to car position
        glMatrix.mat4.rotateY(modelViewMatrix, modelViewMatrix, glMatrix.toRadian(carRotation));
    
        // Draw car body
        drawObject(gl, programInfo, carBody, modelViewMatrix, [1.0, 0.0, 0.0, 1.0]); // Red color
    
        // Draw wheels
        const wheelOffsets = [
            [-0.6, -0.25,  0.4], // Front-left
            [ 0.6, -0.25,  0.4], // Front-right
            [-0.6, -0.25, -0.4], // Rear-left
            [ 0.6, -0.25, -0.4], // Rear-right
        ];
    
        wheelOffsets.forEach((offset, index) => {
            const wheelMatrix = glMatrix.mat4.clone(modelViewMatrix);
            glMatrix.mat4.translate(wheelMatrix, wheelMatrix, offset);
            if (index < 2) {
                // Rotate front wheels to steering angle
                glMatrix.mat4.rotateY(wheelMatrix, wheelMatrix, glMatrix.toRadian(steeringAngle));
            }
            glMatrix.mat4.rotateX(wheelMatrix, wheelMatrix, glMatrix.toRadian(90)); // Align wheels
            drawObject(gl, programInfo, wheel, wheelMatrix, [0.2, 0.2, 0.2, 1.0]); // Dark grey color
        });
    
        // Draw smoke particles
        smokeParticles.forEach((particle) => {
            const particleMatrix = glMatrix.mat4.create();
            glMatrix.mat4.translate(particleMatrix, particleMatrix, particle.position);
            glMatrix.mat4.translate(particleMatrix, particleMatrix, [0, -0.2, 0]);
            glMatrix.mat4.scale(particleMatrix, particleMatrix, [0.2, 0.2, 0.2]);
            drawObject(gl, programInfo, carBody, particleMatrix, [0.5, 0.5, 0.5, particle.life]); // Fade out
        });
    }
    
    // Function to draw an object
    function drawObject(gl, programInfo, buffers, modelViewMatrix, color) {
        // Set shaders
        gl.useProgram(programInfo.program);
    
        // Set attributes
        {
            const numComponents = 3;
            const type = gl.FLOAT;
            gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
            gl.vertexAttribPointer(programInfo.attribLocations.vertexPosition, numComponents, type, false, 0, 0);
            gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
        }
    
        // ... (Set normals and indices similarly)
    
        // Set uniforms
        gl.uniformMatrix4fv(programInfo.uniformLocations.projectionMatrix, false, projectionMatrix);
        gl.uniformMatrix4fv(programInfo.uniformLocations.modelViewMatrix, false, modelViewMatrix);
    
        // Compute normal matrix
        const normalMatrix = glMatrix.mat4.create();
        glMatrix.mat4.invert(normalMatrix, modelViewMatrix);
        glMatrix.mat4.transpose(normalMatrix, normalMatrix);
        gl.uniformMatrix4fv(programInfo.uniformLocations.normalMatrix, false, normalMatrix);
    
        // Set color
        gl.uniform4fv(programInfo.uniformLocations.uColor, color);
    
        // Draw
        gl.drawArrays(gl.TRIANGLES, 0, buffers.vertexCount);
    }
    

    Explanation:

    • Initialization:

      • Set up the WebGL context and shaders.
      • Initialize buffers for the car body and wheels.
    • Car Physics:

      • Use variables to track the car's position, velocity, rotation, and steering angle.
      • The updatePhysics function handles acceleration, braking, and steering based on WASD input.
      • Realistic friction is applied to simulate deceleration over time.
    • Rendering:

      • The drawScene function clears the canvas and sets up the camera and perspective.
      • It draws the car body and wheels, positioning and rotating them appropriately.
      • Front wheels rotate based on the steering angle.
    • Smoke Particles:

      • A simple particle system is implemented using an array of particles.
      • Particles are generated when the car is moving and fade out over time.
      • Each particle moves upwards slightly to simulate smoke.
    • User Input:

      • Event listeners capture key presses and release events to update the keysPressed object.
      • The WASD keys control acceleration and steering.
    • Animation Loop:

      • The render function updates physics and rendering each frame using requestAnimationFrame.

    Notes:

    • Lighting and Normals:

      • The code uses basic lighting calculations in the shaders.
      • Normals need to be calculated for each face of the cube (car body) and the cylinder (wheels).
    • Matrix Calculations:

      • The glMatrix library is used for matrix and vector operations to handle transformations.
    • Performance Enhancements:

      • For a production application, consider optimizing buffer usage and minimizing CPU-GPU data transfer.

    Next Steps:

    • Enhancements:

      • Add more detailed car physics (e.g., torque, drag, suspension).
      • Improve the particle system for more realistic smoke effects.
      • Implement collision detection and response.
    • Visual Improvements:

      • Texture mapping for more detailed appearance.
      • Use more sophisticated shading techniques.

    Feel free to expand upon this code to add more features or refine the simulation.