Create a basic first-person game in a single HTML file, using inline CSS and pure JavaScript. Use gl-matrix exclusively for matrix operations. Implement first-person view with WASD keys for movement (forward, left, backward, right) and mouse for 360-degree rotation and looking around. Map size around 40 square meters (e.g., 6x6 meters). Include floor, ceiling, and solid walls with distinct textures. Prevent bugs like clipping through the map; enforce solid collisions with walls. Textures must be generated using pure math and pure JavaScript only, with no external resources, images, or dependencies beyond gl-matrix.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a complete first-person game in a single HTML file with all the requested features:
html
<!DOCTYPE html>
<html>
<head>
<title>First-Person Game</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
font-family: Arial, sans-serif;
}
canvas {
display: block;
width: 100vw;
height: 100vh;
}
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 5px;
font-size: 14px;
}
</style>
</head>
<body>
<canvas id="glCanvas"></canvas>
<div id="info">WASD to move | Mouse to look | FPS: <span id="fps">0</span></div>
<!-- gl-matrix library -->
<script>
// gl-matrix minified (only the parts we need)
var glMatrix = (function() {
var glMatrix = {};
glMatrix.glMatrix = {};
glMatrix.glMatrix.EPSILON = 0.000001;
glMatrix.glMatrix.ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
glMatrix.glMatrix.RANDOM = Math.random;
var degree = Math.PI / 180;
glMatrix.mat4 = {};
glMatrix.mat4.create = function() {
var out = new glMatrix.glMatrix.ARRAY_TYPE(16);
out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0;
out[4] = 0; out[5] = 1; out[6] = 0; out[7] = 0;
out[8] = 0; out[9] = 0; out[10] = 1; out[11] = 0;
out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1;
return out;
};
glMatrix.mat4.perspective = function(out, fovy, aspect, near, far) {
var f = 1.0 / Math.tan(fovy / 2);
out[0] = f / aspect;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = f;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = (far + near) / (near - far);
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (2 * far * near) / (near - far);
out[15] = 0;
return out;
};
glMatrix.mat4.translate = function(out, a, v) {
var x = v[0], y = v[1], z = v[2];
if (a === out) {
out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
} else {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
out[12] = a00 * x + a10 * y + a20 * z + a[12];
out[13] = a01 * x + a11 * y + a21 * z + a[13];
out[14] = a02 * x + a12 * y + a22 * z + a[14];
out[15] = a03 * x + a13 * y + a23 * z + a[15];
}
return out;
};
glMatrix.mat4.rotate = function(out, a, rad, axis) {
var x = axis[0], y = axis[1], z = axis[2];
var len = Math.sqrt(x * x + y * y + z * z);
len = len !== 0 ? 1 / len : 0;
x *= len;
y *= len;
z *= len;
var s = Math.sin(rad);
var c = Math.cos(rad);
var t = 1 - c;
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
var b00 = x * x * t + c, b01 = y * x * t + z * s, b02 = z * x * t - y * s;
var b10 = x * y * t - z * s, b11 = y * y * t + c, b12 = z * y * t + x * s;
var b20 = x * z * t + y * s, b21 = y * z * t - x * s, b22 = z * z * t + c;
out[0] = a00 * b00 + a10 * b01 + a20 * b02;
out[1] = a01 * b00 + a11 * b01 + a21 * b02;
out[2] = a02 * b00 + a12 * b01 + a22 * b02;
out[3] = a03 * b00 + a13 * b01 + a23 * b02;
out[4] = a00 * b10 + a10 * b11 + a20 * b12;
out[5] = a01 * b10 + a11 * b11 + a21 * b12;
out[6] = a02 * b10 + a12 * b11 + a22 * b12;
out[7] = a03 * b10 + a13 * b11 + a23 * b12;
out[8] = a00 * b20 + a10 * b21 + a20 * b22;
out[9] = a01 * b20 + a11 * b21 + a21 * b22;
out[10] = a02 * b20 + a12 * b21 + a22 * b22;
out[11] = a03 * b20 + a13 * b21 + a23 * b22;
if (a !== out) {
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
return out;
};
glMatrix.vec3 = {};
glMatrix.vec3.create = function() {
var out = new glMatrix.glMatrix.ARRAY_TYPE(3);
out[0] = 0;
out[1] = 0;
out[2] = 0;
return out;
};
glMatrix.vec3.normalize = function(out, a) {
var x = a[0], y = a[1], z = a[2];
var len = x * x + y * y + z * z;
if (len > 0) {
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
out[2] = a[2] * len;
}
return out;
};
glMatrix.vec3.cross = function(out, a, b) {
var ax = a[0], ay = a[1], az = a[2];
var bx = b[0], by = b[1], bz = b[2];
out[0] = ay * bz - az * by;
out[1] = az * bx - ax * bz;
out[2] = ax * by - ay * bx;
return out;
};
return glMatrix;
})();
</script>
<script>
// Game constants
const MAP_SIZE = 6; // 6x6 meters
const WALL_HEIGHT = 2.5;
const PLAYER_HEIGHT = 1.8;
const PLAYER_SPEED = 0.1;
const MOUSE_SENSITIVITY = 0.002;
const FLOOR_TEXTURE_SIZE = 0.5;
const WALL_TEXTURE_SIZE = 0.25;
const CEILING_TEXTURE_SIZE = 0.5;
// Game state
let player = {
position: [0, PLAYER_HEIGHT, 0],
rotation: [0, 0], // yaw, pitch
velocity: [0, 0, 0],
moving: { forward: false, backward: false, left: false, right: false }
};
let mouse = {
x: 0,
y: 0,
lastX: 0,
lastY: 0,
locked: false
};
let lastTime = 0;
let fps = 0;
let frameCount = 0;
let lastFpsTime = 0;
// WebGL setup
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
if (!gl) {
alert('WebGL not supported in your browser');
throw new Error('WebGL not supported');
}
// Resize canvas to full window
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
gl.viewport(0, 0, canvas.width, canvas.height);
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// Shader programs
const vertexShaderSource = `
attribute vec3 aPosition;
attribute vec2 aTexCoord;
attribute vec3 aNormal;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
uniform mat3 uNormalMatrix;
varying vec2 vTexCoord;
varying vec3 vNormal;
varying vec3 vPosition;
void main() {
gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 1.0);
vTexCoord = aTexCoord;
vNormal = uNormalMatrix * aNormal;
vPosition = aPosition;
}
`;
const fragmentShaderSource = `
precision mediump float;
varying vec2 vTexCoord;
varying vec3 vNormal;
varying vec3 vPosition;
uniform vec3 uLightPosition;
uniform vec3 uLightColor;
uniform vec3 uAmbientColor;
uniform int uTextureType; // 0=floor, 1=wall, 2=ceiling
vec3 generateFloorTexture(vec2 coord) {
vec2 scaledCoord = coord * 10.0;
vec2 grid = abs(fract(scaledCoord) - 0.5);
float checker = step(0.45, grid.x) * step(0.45, grid.y);
vec3 color1 = mix(vec3(0.8, 0.7, 0.5), vec3(0.6, 0.5, 0.3), checker);
vec3 color2 = mix(vec3(0.3, 0.3, 0.3), vec3(0.1, 0.1, 0.1), checker);
return mix(color1, color2, 0.5);
}
vec3 generateWallTexture(vec2 coord) {
vec2 scaledCoord = coord * 20.0;
float bricks = fract(scaledCoord.y * 5.0);
float mortar = step(0.9, bricks) * step(0.05, fract(scaledCoord.x * 10.0));
vec3 brickColor = mix(vec3(0.7, 0.2, 0.1), vec3(0.5, 0.1, 0.05), mortar);
vec3 mortarColor = vec3(0.4, 0.4, 0.4);
return mix(brickColor, mortarColor, mortar);
}
vec3 generateCeilingTexture(vec2 coord) {
vec2 scaledCoord = coord * 5.0;
float pattern = sin(scaledCoord.x * 10.0) * cos(scaledCoord.y * 10.0);
vec3 color = mix(vec3(0.7, 0.7, 0.8), vec3(0.5, 0.5, 0.6), pattern * 0.5 + 0.5);
return color;
}
void main() {
vec3 normal = normalize(vNormal);
vec3 lightDirection = normalize(uLightPosition - vPosition);
float diffuse = max(dot(normal, lightDirection), 0.0);
vec3 diffuseColor = uLightColor * diffuse;
vec3 textureColor;
if (uTextureType == 0) {
textureColor = generateFloorTexture(vTexCoord);
} else if (uTextureType == 1) {
textureColor = generateWallTexture(vTexCoord);
} else {
textureColor = generateCeilingTexture(vTexCoord);
}
vec3 finalColor = (uAmbientColor + diffuseColor) * textureColor;
gl_FragColor = vec4(finalColor, 1.0);
}
`;
function compileShader(gl, source, type) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error('Shader compilation error:', gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
const vertexShader = compileShader(gl, vertexShaderSource, gl.VERTEX_SHADER);
const fragmentShader = compileShader(gl, fragmentShaderSource, gl.FRAGMENT_SHADER);
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
console.error('Shader program linking error:', gl.getProgramInfoLog(shaderProgram));
}
// Get attribute and uniform locations
const programInfo = {
program: shaderProgram,
attribLocations: {
position: gl.getAttribLocation(shaderProgram, 'aPosition'),
texCoord: gl.getAttribLocation(shaderProgram, 'aTexCoord'),
normal: gl.getAttribLocation(shaderProgram, 'aNormal'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
normalMatrix: gl.getUniformLocation(shaderProgram, 'uNormalMatrix'),
lightPosition: gl.getUniformLocation(shaderProgram, 'uLightPosition'),
lightColor: gl.getUniformLocation(shaderProgram, 'uLightColor'),
ambientColor: gl.getUniformLocation(shaderProgram, 'uAmbientColor'),
textureType: gl.getUniformLocation(shaderProgram, 'uTextureType'),
},
};
// Initialize buffers
function initBuffers() {
// Create a buffer for the cube's vertex positions
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Create a buffer for the cube's texture coordinates
const textureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);
// Create a buffer for the cube's vertex normals
const normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
// Create a buffer for the cube's indices
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
return {
position: positionBuffer,
textureCoord: textureCoordBuffer,
normal: normalBuffer,
indices: indexBuffer,
};
}
const buffers = initBuffers();
// Create map data
const map = [
[1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1]
];
// Generate geometry for the map
function generateMapGeometry() {
const positions = [];
const textureCoords = [];
const normals = [];
const indices = [];
let index = 0;
// Generate floor
for (let z = 0; z < MAP_SIZE; z++) {
for (let x = 0; x < MAP_SIZE; x++) {
if (map[z][x] === 0) {
// Floor vertices
positions.push(
x, 0, z,
x + 1, 0, z,
x + 1, 0, z + 1,
x, 0, z + 1
);
// Floor texture coordinates
textureCoords.push(
0, 0,
FLOOR_TEXTURE_SIZE, 0,
FLOOR_TEXTURE_SIZE, FLOOR_TEXTURE_SIZE,
0, FLOOR_TEXTURE_SIZE
);
// Floor normals (pointing up)
normals.push(
0, 1, 0,
0, 1, 0,
0, 1, 0,
0, 1, 0
);
// Floor indices
indices.push(
index, index + 1, index + 2,
index, index + 2, index + 3
);
index += 4;
}
}
}
// Generate ceiling
for (let z = 0; z < MAP_SIZE; z++) {
for (let x = 0; x < MAP_SIZE; x++) {
if (map[z][x] === 0) {
// Ceiling vertices
positions.push(
x, WALL_HEIGHT, z,
x + 1, WALL_HEIGHT, z,
x + 1, WALL_HEIGHT, z + 1,
x, WALL_HEIGHT, z + 1
);
// Ceiling texture coordinates
textureCoords.push(
0, 0,
CEILING_TEXTURE_SIZE, 0,
CEILING_TEXTURE_SIZE, CEILING_TEXTURE_SIZE,
0, CEILING_TEXTURE_SIZE
);
// Ceiling normals (pointing down)
normals.push(
0, -1, 0,
0, -1, 0,
0, -1, 0,
0, -1, 0
);
// Ceiling indices
indices.push(
index, index + 2, index + 1,
index, index + 3, index + 2
);
index += 4;
}
}
}
// Generate walls
for (let z = 0; z < MAP_SIZE; z++) {
for (let x = 0; x < MAP_SIZE; x++) {
if (map[z][x] === 1) {
// Check adjacent cells to determine which walls to draw
// North wall (z+1)
if (z + 1 >= MAP_SIZE || map[z + 1][x] === 0) {
positions.push(
x, 0, z + 1,
x + 1, 0, z + 1,
x + 1, WALL_HEIGHT, z + 1,
x, WALL_HEIGHT, z + 1
);
textureCoords.push(
0, 0,
WALL_TEXTURE_SIZE, 0,
WALL_TEXTURE_SIZE, WALL_TEXTURE_SIZE,
0, WALL_TEXTURE_SIZE
);
normals.push(
0, 0, -1,
0, 0, -1,
0, 0, -1,
0, 0, -1
);
indices.push(
index, index + 1, index + 2,
index, index + 2, index + 3
);
index += 4;
}
// South wall (z-1)
if (z - 1 < 0 || map[z - 1][x] === 0) {
positions.push(
x, 0, z,
x, WALL_HEIGHT, z,
x + 1, WALL_HEIGHT, z,
x + 1, 0, z
);
textureCoords.push(
0, 0,
0, WALL_TEXTURE_SIZE,
WALL_TEXTURE_SIZE, WALL_TEXTURE_SIZE,
WALL_TEXTURE_SIZE, 0
);
normals.push(
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, 1
);
indices.push(
index, index + 1, index + 2,
index, index + 2, index + 3
);
index += 4;
}
// East wall (x+1)
if (x + 1 >= MAP_SIZE || map[z][x + 1] === 0) {
positions.push(
x + 1, 0, z,
x + 1, 0, z + 1,
x + 1, WALL_HEIGHT, z + 1,
x + 1, WALL_HEIGHT, z
);
textureCoords.push(
0, 0,
WALL_TEXTURE_SIZE, 0,
WALL_TEXTURE_SIZE, WALL_TEXTURE_SIZE,
0, WALL_TEXTURE_SIZE
);
normals.push(
-1, 0, 0,
-1, 0, 0,
-1, 0, 0,
-1, 0, 0
);
indices.push(
index, index + 1, index + 2,
index, index + 2, index + 3
);
index += 4;
}
// West wall (x-1)
if (x - 1 < 0 || map[z][x - 1] === 0) {
positions.push(
x, 0, z + 1,
x, WALL_HEIGHT, z + 1,
x, WALL_HEIGHT, z,
x, 0, z
);
textureCoords.push(
0, 0,
0, WALL_TEXTURE_SIZE,
WALL_TEXTURE_SIZE, WALL_TEXTURE_SIZE,
WALL_TEXTURE_SIZE, 0
);
normals.push(
1, 0, 0,
1, 0, 0,
1, 0, 0,
1, 0, 0
);
indices.push(
index, index + 1, index + 2,
index, index + 2, index + 3
);
index += 4;
}
}
}
}
// Convert to typed arrays
const positionArray = new Float32Array(positions);
const textureCoordArray = new Float32Array(textureCoords);
const normalArray = new Float32Array(normals);
const indexArray = new Uint16Array(indices);
// Bind position buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.bufferData(gl.ARRAY_BUFFER, positionArray, gl.STATIC_DRAW);
// Bind texture coordinate buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);
gl.bufferData(gl.ARRAY_BUFFER, textureCoordArray, gl.STATIC_DRAW);
// Bind normal buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);
gl.bufferData(gl.ARRAY_BUFFER, normalArray, gl.STATIC_DRAW);
// Bind index buffer
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indexArray, gl.STATIC_DRAW);
return {
vertexCount: indices.length,
floorCount: (MAP_SIZE - 2) * (MAP_SIZE - 2) * 6,
ceilingCount: (MAP_SIZE - 2) * (MAP_SIZE - 2) * 6,
wallCount: indices.length - (MAP_SIZE - 2) * (MAP_SIZE - 2) * 12
};
}
const geometryInfo = generateMapGeometry();
// Input handling
function setupInput() {
document.addEventListener('keydown', function(event) {
switch (event.key.toLowerCase()) {
case 'w': player.moving.forward = true; break;
case 's': player.moving.backward = true; break;
case 'a': player.moving.left = true; break;
case 'd': player.moving.right = true; break;
}
});
document.addEventListener('keyup', function(event) {
switch (event.key.toLowerCase()) {
case 'w': player.moving.forward = false; break;
case 's': player.moving.backward = false; break;
case 'a': player.moving.left = false; break;
case 'd': player.moving.right = false; break;
}
});
canvas.addEventListener('mousedown', function() {
if (!mouse.locked) {
canvas.requestPointerLock = canvas.requestPointerLock ||
canvas.mozRequestPointerLock ||
canvas.webkitRequestPointerLock;
canvas.requestPointerLock();
}
});
document.addEventListener('pointerlockchange', function() {
mouse.locked = document.pointerLockElement === canvas ||
document.mozPointerLockElement === canvas ||
document.webkitPointerLockElement === canvas;
}, false);
document.addEventListener('mousemove', function(event) {
if (mouse.locked) {
const movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
const movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
player.rotation[0] -= movementX * MOUSE_SENSITIVITY;
player.rotation[1] -= movementY * MOUSE_SENSITIVITY;
// Clamp pitch to prevent over-rotation
player.rotation[1] = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, player.rotation[1]));
}
});
}
// Collision detection
function checkCollision(newX, newZ) {
// Convert player position to grid coordinates
const gridX = Math.floor(newX);
const gridZ = Math.floor(newZ);
// Check if the new position is within the map bounds
if (gridX < 0 || gridX >= MAP_SIZE || gridZ < 0 || gridZ >= MAP_SIZE) {
return true;
}
// Check if the new position is in a wall
return map[gridZ][gridX] === 1;
}
// Update player position
function updatePlayer(deltaTime) {
const moveSpeed = PLAYER_SPEED * deltaTime;
// Calculate movement direction based on rotation
const yaw = player.rotation[0];
const forwardX = Math.sin(yaw);
const forwardZ = Math.cos(yaw);
const rightX = Math.sin(yaw - Math.PI / 2);
const rightZ = Math.cos(yaw - Math.PI / 2);
let newX = player.position[0];
let newZ = player.position[2];
// Handle movement
if (player.moving.forward) {
newX += forwardX * moveSpeed;
newZ += forwardZ * moveSpeed;
}
if (player.moving.backward) {
newX -= forwardX * moveSpeed;
newZ -= forwardZ * moveSpeed;
}
if (player.moving.left) {
newX += rightX * moveSpeed;
newZ += rightZ * moveSpeed;
}
if (player.moving.right) {
newX -= rightX * moveSpeed;
newZ -= rightZ * moveSpeed;
}
// Check for collisions
if (!checkCollision(newX, newZ)) {
player.position[0] = newX;
player.position[2] = newZ;
} else {
// Try moving only in X direction
if (!checkCollision(newX, player.position[2])) {
player.position[0] = newX;
}
// Try moving only in Z direction
if (!checkCollision(player.position[0], newZ)) {
player.position[2] = newZ;
}
}
}
// Draw the scene
function drawScene() {
gl.clearColor(0.0, 0.0, 0.0, 1.0);
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 = 45 * Math.PI / 180;
const aspect = canvas.width / canvas.height;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = glMatrix.mat4.create();
glMatrix.mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Create model-view matrix
const modelViewMatrix = glMatrix.mat4.create();
// Move the drawing position to where we want to start drawing
glMatrix.mat4.translate(modelViewMatrix, modelViewMatrix, [
-player.position[0],
-player.position[1],
-player.position[2]
]);
// Rotate based on player's view
glMatrix.mat4.rotate(modelViewMatrix, modelViewMatrix, player.rotation[1], [1, 0, 0]); // Pitch
glMatrix.mat4.rotate(modelViewMatrix, modelViewMatrix, player.rotation[0], [0, 1, 0]); // Yaw
// Calculate normal matrix
const normalMatrix = glMatrix.mat3.create();
glMatrix.mat3.normalFromMat4(normalMatrix, modelViewMatrix);
// Tell WebGL how to pull out the positions from position buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.position,
3, // 3 components per iteration
gl.FLOAT, // data type
false, // normalize
0, // stride
0 // offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.position);
// Tell WebGL how to pull out the texture coordinates from texture coordinate buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);
gl.vertexAttribPointer(
programInfo.attribLocations.texCoord,
2, // 2 components per iteration
gl.FLOAT, // data type
false, // normalize
0, // stride
0 // offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.texCoord);
// Tell WebGL how to pull out the normals from normal buffer
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);
gl.vertexAttribPointer(
programInfo.attribLocations.normal,
3, // 3 components per iteration
gl.FLOAT, // data type
false, // normalize
0, // stride
0 // offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.normal);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
gl.uniformMatrix3fv(
programInfo.uniformLocations.normalMatrix,
false,
normalMatrix
);
gl.uniform3fv(programInfo.uniformLocations.lightPosition, [2.5, 3.0, 2.5]);
gl.uniform3fv(programInfo.uniformLocations.lightColor, [1.0, 1.0, 1.0]);
gl.uniform3fv(programInfo.uniformLocations.ambientColor, [0.2, 0.2, 0.2]);
// Draw the floor
gl.uniform1i(programInfo.uniformLocations.textureType, 0);
gl.drawElements(
gl.TRIANGLES,
geometryInfo.floorCount,
gl.UNSIGNED_SHORT,
0
);
// Draw the walls
gl.uniform1i(programInfo.uniformLocations.textureType, 1);
gl.drawElements(
gl.TRIANGLES,
geometryInfo.wallCount,
gl.UNSIGNED_SHORT,
geometryInfo.floorCount * 2 // Skip floor vertices
);
// Draw the ceiling
gl.uniform1i(programInfo.uniformLocations.textureType, 2);
gl.drawElements(
gl.TRIANGLES,
geometryInfo.ceilingCount,
gl.UNSIGNED_SHORT,
(geometryInfo.floorCount + geometryInfo.wallCount) * 2 // Skip floor and wall vertices
);
}
// Main render loop
function render(currentTime) {
currentTime *= 0.001; // Convert to seconds
const deltaTime = currentTime - lastTime;
lastTime = currentTime;
// Update FPS counter
frameCount++;
if (currentTime - lastFpsTime >= 1.0) {
fps = frameCount;
frameCount = 0;
lastFpsTime = currentTime;
document.getElementById('fps').textContent = fps;
}
updatePlayer(deltaTime);
drawScene();
requestAnimationFrame(render);
}
// Initialize and start the game
setupInput();
requestAnimationFrame(render);
</script>
</body>
</html>
Features Implemented:
First-Person View: Full 3D perspective with mouse look and keyboard movement
Movement Controls:
WASD keys for movement (forward, backward, left, right)
Mouse for 360-degree rotation and looking around
Map:
6x6 meter map (as requested)
Floor, ceiling, and walls with distinct procedurally generated textures
Collision Detection:
Prevents clipping through walls
Solid collisions with proper physics response
Textures:
All textures generated with pure math (no external resources)
Floor: Checkerboard pattern
Walls: Brick pattern
Ceiling: Wavy pattern
Performance:
FPS counter
Proper WebGL rendering with depth testing
The game uses gl-matrix for all matrix operations as requested, and all textures are generated procedurally with JavaScript math functions. The collision detection prevents the player from moving through walls while allowing smooth movement in open areas.