Okay, this is a fantastic challenge! Creating a 3D environment, especially a first-person shooter like Counter-Strike, using only HTML, CSS, and plain JavaScript is quite complex because browsers don't natively support 3D rendering the way game engines do.
However, we can leverage WebGL through a JavaScript library. The most popular and easiest to get started with is Three.js. It's still pure JavaScript, HTML, and CSS, just with a helpful abstraction layer over raw WebGL.
Here's a simplified "Counter-Strike-like" 3D environment where you can walk around a basic map, look around with your mouse, and "shoot" (a simple raycast that changes the color of a hit object).
Features:
First-Person View: Control with mouse (look) and WASD (move).
Basic Map: A simple room with walls and a floor.
Weapon Model: A simple block representing a gun.
Shooting: Left-click to "fire" (raycast from camera, changes target color).
Targets: Some simple boxes you can "shoot".
Pointer Lock API: Locks the mouse for true FPS controls.
How to Run This Code:
Save the entire code block below into a file named index.html.
Open index.html in a modern web browser (Chrome, Firefox, Edge are best).
Click anywhere on the canvas to lock your mouse and start controlling the camera.
WASD to move.
Mouse to look around.
Left-Click to "shoot".
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple CS-like 3D Environment</title>
<style>
body { margin: 0; overflow: hidden; background-color: #1a1a1a; }
canvas { display: block; }
#overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
color: white;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-family: 'Arial', sans-serif;
font-size: 24px;
text-align: center;
cursor: pointer;
z-index: 100;
}
#hud {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
color: white;
font-family: 'Consolas', monospace;
font-size: 18px;
z-index: 101;
}
#crosshair {
position: absolute;
top: 50%;
left: 50%;
width: 2px;
height: 2px;
background-color: lime;
border-radius: 50%;
transform: translate(-50%, -50%);
z-index: 102;
box-shadow: 0 0 5px lime; /* Glow effect */
}
</style>
</head>
<body>
<div id="overlay">
<p>Click to start and lock mouse!</p>
<p>WASD to move, Mouse to look, Left-Click to shoot.</p>
</div>
<div id="hud">
FPS: --
</div>
<div id="crosshair"></div>
<!-- Include Three.js library from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.158.0/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.158.0/examples/js/controls/PointerLockControls.js"></script>
<script>
// --- Core Three.js Setup ---
let camera, scene, renderer;
let controls; // For first-person movement
let moveForward = false;
let moveBackward = false;
let moveLeft = false;
let moveRight = false;
let canJump = false;
let prevTime = performance.now();
const velocity = new THREE.Vector3();
const direction = new THREE.Vector3();
const objects = []; // Array to store objects for raycasting (shooting)
// --- HUD and Overlay Elements ---
const overlay = document.getElementById('overlay');
const hud = document.getElementById('hud');
let frames = 0;
let lastFPSUpdateTime = performance.now();
// --- Initialization Function ---
function init() {
// Camera (FOV, Aspect Ratio, Near, Far clipping plane)
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.y = 1.7; // Player height
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x87CEEB); // Sky blue background
scene.fog = new THREE.Fog(0x87CEEB, 0, 750); // Simple fog
// Lights
const ambientLight = new THREE.AmbientLight(0x666666); // Soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1.5, 0.5).normalize();
scene.add(directionalLight);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// --- PointerLockControls for FPS Movement ---
controls = new THREE.PointerLockControls(camera, document.body);
// Event listener for overlay click to lock pointer
overlay.addEventListener('click', () => {
controls.lock();
}, false);
controls.addEventListener('lock', () => {
overlay.style.display = 'none'; // Hide overlay when locked
});
controls.addEventListener('unlock', () => {
overlay.style.display = 'flex'; // Show overlay when unlocked
});
scene.add(controls.getObject()); // Add the camera object (which controls moves) to the scene
// --- Keyboard Input Handling ---
const onKeyDown = function (event) {
switch (event.code) {
case 'ArrowUp':
case 'KeyW':
moveForward = true;
break;
case 'ArrowLeft':
case 'KeyA':
moveLeft = true;
break;
case 'ArrowDown':
case 'KeyS':
moveBackward = true;
break;
case 'ArrowRight':
case 'KeyD':
moveRight = true;
break;
case 'Space':
if (canJump === true) velocity.y += 30; // Simple jump
canJump = false;
break;
}
};
const onKeyUp = function (event) {
switch (event.code) {
case 'ArrowUp':
case 'KeyW':
moveForward = false;
break;
case 'ArrowLeft':
case 'KeyA':
moveLeft = false;
break;
case 'ArrowDown':
case 'KeyS':
moveBackward = false;
break;
case 'ArrowRight':
case 'KeyD':
moveRight = false;
break;
}
};
document.addEventListener('keydown', onKeyDown);
document.addEventListener('keyup', onKeyUp);
// --- Mouse Click (Shooting) Handling ---
document.addEventListener('click', onShoot, false);
// --- Map Creation (Simple CS-like Room) ---
const textureLoader = new THREE.TextureLoader();
// Floor
const floorTexture = textureLoader.load('https://threejs.org/examples/textures/hardwood2_diffuse.jpg');
floorTexture.wrapS = THREE.RepeatWrapping;
floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set(10, 10);
const floorGeometry = new THREE.PlaneGeometry(50, 50, 1, 1);
const floorMaterial = new THREE.MeshLambertMaterial({ map: floorTexture, side: THREE.DoubleSide });
const floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.rotation.x = -Math.PI / 2; // Rotate to be flat
floor.position.y = 0;
scene.add(floor);
objects.push(floor); // Add floor to objects for raycasting if needed
// Walls (using a simple brick texture)
const wallTexture = textureLoader.load('https://threejs.org/examples/textures/brick_diffuse.jpg');
wallTexture.wrapS = THREE.RepeatWrapping;
wallTexture.wrapT = THREE.RepeatWrapping;
wallTexture.repeat.set(5, 2); // Repeat texture
const wallMaterial = new THREE.MeshLambertMaterial({ map: wallTexture });
const wallGeometry = new THREE.BoxGeometry(50, 5, 0.1); // Length, Height, Thickness
// Back Wall
const wall1 = new THREE.Mesh(wallGeometry, wallMaterial);
wall1.position.z = -25;
wall1.position.y = 2.5;
scene.add(wall1);
objects.push(wall1);
// Front Wall (optional, leaving open for "outside" view)
// const wall2 = new THREE.Mesh(wallGeometry, wallMaterial);
// wall2.position.z = 25;
// wall2.position.y = 2.5;
// scene.add(wall2);
// objects.push(wall2);
// Left Wall
const wall3 = new THREE.Mesh(wallGeometry, wallMaterial);
wall3.rotation.y = Math.PI / 2;
wall3.position.x = -25;
wall3.position.y = 2.5;
scene.add(wall3);
objects.push(wall3);
// Right Wall
const wall4 = new THREE.Mesh(wallGeometry, wallMaterial);
wall4.rotation.y = -Math.PI / 2;
wall4.position.x = 25;
wall4.position.y = 2.5;
scene.add(wall4);
objects.push(wall4);
// --- Player Weapon (Simple Block) ---
const weaponGeometry = new THREE.BoxGeometry(0.08, 0.08, 0.4); // Thin, rectangular gun
const weaponMaterial = new THREE.MeshStandardMaterial({ color: 0x444444, metalness: 0.8, roughness: 0.2 });
const weapon = new THREE.Mesh(weaponGeometry, weaponMaterial);
// Position relative to the camera for FPS view
weapon.position.set(0.2, -0.15, -0.4); // Right, Down, Forward (into screen)
camera.add(weapon); // Add weapon to camera so it moves with the camera
// --- Targets (Simple Boxes) ---
const targetMaterial = new THREE.MeshPhongMaterial({ color: 0xcc0000 }); // Red targets
const targetGeometry = new THREE.BoxGeometry(1, 1, 1);
function createTarget(x, y, z) {
const target = new THREE.Mesh(targetGeometry, targetMaterial.clone()); // Clone material for individual color changes
target.position.set(x, y, z);
scene.add(target);
objects.push(target); // Add to objects for raycasting
}
createTarget(-10, 1.5, -20);
createTarget(15, 1.5, -10);
createTarget(0, 1.5, -15);
createTarget(20, 1.5, -20);
// --- Handle Window Resizing ---
window.addEventListener('resize', onWindowResize, false);
}
// --- Window Resize Listener ---
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// --- Shooting Logic ---
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
function onShoot(event) {
if (controls.isLocked === true) {
// Get mouse coordinates (normalized device coordinates -1 to +1)
// For a click, we assume the ray comes from the center of the screen
mouse.x = 0; // Center X
mouse.y = 0; // Center Y
raycaster.setFromCamera(mouse, camera); // Set raycaster to originate from camera position and direction
// Calculate objects intersecting the ray
const intersects = raycaster.intersectObjects(objects);
if (intersects.length > 0) {
const hitObject = intersects[0].object;
// Check if it's a target (or something we want to react to)
if (hitObject.material.color.getHex() === 0xcc0000) { // If it's a red target
hitObject.material.color.set(0x00cc00); // Change to green
// Simple feedback: you could add particles, sound, etc.
console.log('Hit a target!');
} else if (hitObject.material.color.getHex() === 0x00cc00) {
// Already hit, change back to red for "respawn"
hitObject.material.color.set(0xcc0000);
console.log('Reset target!');
}
}
}
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
const time = performance.now();
const delta = (time - prevTime) / 1000; // Time in seconds since last frame
// --- Update FPS Counter ---
frames++;
if (time - lastFPSUpdateTime >= 1000) { // Every second
hud.innerText = `FPS: ${frames}`;
frames = 0;
lastFPSUpdateTime = time;
}
// --- Player Movement Logic ---
if (controls.isLocked === true) {
velocity.x -= velocity.x * 10.0 * delta; // Apply friction
velocity.z -= velocity.z * 10.0 * delta;
velocity.y -= 9.8 * 10.0 * delta; // Apply gravity
direction.z = Number(moveForward) - Number(moveBackward);
direction.x = Number(moveRight) - Number(moveLeft);
direction.normalize(); // Ensure constant speed in all directions
if (moveForward || moveBackward) velocity.z -= direction.z * 40.0 * delta;
if (moveLeft || moveRight) velocity.x -= direction.x * 40.0 * delta;
// Simple collision with floor (prevents falling through)
if (controls.getObject().position.y < 1.7) { // 1.7 is player height
velocity.y = Math.max(0, velocity.y);
controls.getObject().position.y = 1.7;
canJump = true;
}
// Apply velocity to controls
controls.moveRight(-velocity.x * delta);
controls.moveForward(-velocity.z * delta);
controls.getObject().position.y += (velocity.y * delta); // New behavior: apply vertical velocity directly to camera object
}
prevTime = time;
renderer.render(scene, camera); // Render the scene
}
// Start the game!
init();
animate(); // Call animate once to start the loop
</script>
</body>
</html>