<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>First-Person…
- User
- Assistant
Adding a gun to your first-person shooter (FPS) game enhances the immersion and provides a more authentic shooting experience. Below, I'll guide you through the steps to add a simple gun model to your game using Three.js. We'll create a basic gun using simple geometries and attach it to the camera so that it moves naturally with the player's view. Additionally, we'll implement a basic recoil effect when shooting.
Below is the complete HTML and JavaScript code with the gun added. Comments are included to highlight the new sections and explain their functionality.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First-Person Shooter Game with House and Gun</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
}
canvas {
display: block;
}
#instructions {
position: absolute;
top: 50%;
width: 100%;
text-align: center;
color: white;
font-family: Arial, sans-serif;
font-size: 24px;
user-select: none;
cursor: pointer;
transform: translateY(-50%);
}
</style>
<!-- Import Map to resolve 'three' module -->
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.152.0/build/three.module.js"
}
}
</script>
</head>
<body>
<div id="instructions">
Click to Play<br>
W/A/S/D to Move | Mouse to Look | Click to Shoot
</div>
<script type="module">
// Import Three.js and PointerLockControls as ES6 modules using import map and absolute URLs
import * as THREE from 'three'; // Resolved via import map
import { PointerLockControls } from 'https://cdn.jsdelivr.net/npm/three@0.152.0/examples/jsm/controls/PointerLockControls.js';
// Setup Scene, Camera, and Renderer
const scene = new THREE.Scene();
// Set the sky to a solid blue color
scene.background = new THREE.Color(0x87ceeb); // Sky Blue
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio( window.devicePixelRatio );
renderer.shadowMap.enabled = true; // Enable shadows
document.body.appendChild(renderer.domElement);
// Add Lighting
const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444, 1.0);
hemiLight.position.set(0, 200, 0);
scene.add(hemiLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
dirLight.position.set(0, 200, 100);
dirLight.castShadow = true;
dirLight.shadow.camera.top = 180;
dirLight.shadow.camera.bottom = -100;
dirLight.shadow.camera.left = -120;
dirLight.shadow.camera.right = 120;
scene.add(dirLight);
// ---------- Add Green Ground ----------
const groundMaterial = new THREE.MeshPhongMaterial({
color: 0x00ff00 // Green color
});
const groundGeometry = new THREE.PlaneGeometry(1000, 1000);
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = - Math.PI / 2; // Rotate to make it horizontal
ground.receiveShadow = true; // Allow ground to receive shadows
scene.add(ground);
// ---------- Add Some Red Cubes as Targets ----------
const boxGeometry = new THREE.BoxGeometry(20, 20, 20);
const boxMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000 }); // Red color
const targets = [];
for (let i = 0; i < 20; i++) {
const box = new THREE.Mesh(boxGeometry, boxMaterial);
box.position.set(
Math.random() * 800 - 400,
10,
Math.random() * 800 - 400
);
box.castShadow = true;
box.receiveShadow = true;
scene.add(box);
targets.push(box);
}
// ---------- Add a House with Windows and Doors ----------
function createHouse() {
const house = new THREE.Group();
// ----- Walls -----
const wallsMaterial = new THREE.MeshPhongMaterial({ color: 0x8B4513 }); // Brown color for walls
const wallsGeometry = new THREE.BoxGeometry(100, 60, 100);
const walls = new THREE.Mesh(wallsGeometry, wallsMaterial);
walls.castShadow = true;
walls.receiveShadow = true;
walls.position.y = 30; // Raise walls to sit on the ground
house.add(walls);
// ----- Roof -----
const roofMaterial = new THREE.MeshPhongMaterial({ color: 0xB22222 }); // Firebrick color for roof
const roofGeometry = new THREE.ConeGeometry(70, 30, 4); // Square base
const roof = new THREE.Mesh(roofGeometry, roofMaterial);
roof.rotation.y = Math.PI / 4; // Rotate to align with walls
roof.position.y = 60; // Position atop the walls
roof.castShadow = true;
roof.receiveShadow = true;
house.add(roof);
// ----- Door -----
const doorMaterial = new THREE.MeshPhongMaterial({ color: 0x654321 }); // Dark brown for door
const doorGeometry = new THREE.BoxGeometry(20, 35, 5);
const door = new THREE.Mesh(doorGeometry, doorMaterial);
door.position.set(0, 17.5, 52.51); // Position on the front face of walls
door.castShadow = true;
door.receiveShadow = true;
house.add(door);
// ----- Windows -----
const windowMaterial = new THREE.MeshPhongMaterial({
color: 0xADD8E6, // Light blue for windows
transparent: true,
opacity: 0.6
});
const windowGeometry = new THREE.BoxGeometry(15, 15, 2);
// Front Window
const frontWindow = new THREE.Mesh(windowGeometry, windowMaterial);
frontWindow.position.set(-30, 30, 52.51); // Left front window
house.add(frontWindow);
const frontWindow2 = new THREE.Mesh(windowGeometry, windowMaterial);
frontWindow2.position.set(30, 30, 52.51); // Right front window
house.add(frontWindow2);
// Back Window
const backWindow = new THREE.Mesh(windowGeometry, windowMaterial);
backWindow.position.set(-30, 30, -52.51); // Left back window
house.add(backWindow);
const backWindow2 = new THREE.Mesh(windowGeometry, windowMaterial);
backWindow2.position.set(30, 30, -52.51); // Right back window
house.add(backWindow2);
// ----- Side Windows -----
const sideWindow = new THREE.Mesh(windowGeometry, windowMaterial);
sideWindow.position.set(52.51, 30, 30); // Right side window
sideWindow.rotation.y = Math.PI / 2;
house.add(sideWindow);
const sideWindow2 = new THREE.Mesh(windowGeometry, windowMaterial);
sideWindow2.position.set(52.51, 30, -30); // Right side window
sideWindow2.rotation.y = Math.PI / 2;
house.add(sideWindow2);
const sideWindow3 = new THREE.Mesh(windowGeometry, windowMaterial);
sideWindow3.position.set(-52.51, 30, 30); // Left side window
sideWindow3.rotation.y = Math.PI / 2;
house.add(sideWindow3);
const sideWindow4 = new THREE.Mesh(windowGeometry, windowMaterial);
sideWindow4.position.set(-52.51, 30, -30); // Left side window
sideWindow4.rotation.y = Math.PI / 2;
house.add(sideWindow4);
return house;
}
// Create and position the house
const house = createHouse();
house.position.set(0, 0, -200); // Position the house 200 units behind the starting point
scene.add(house);
// ---------- Pointer Lock Controls ----------
const controls = new PointerLockControls(camera, document.body);
const instructions = document.getElementById('instructions');
instructions.addEventListener('click', () => {
controls.lock();
}, false);
controls.addEventListener('lock', () => {
instructions.style.display = 'none';
});
controls.addEventListener('unlock', () => {
instructions.style.display = '';
});
scene.add(controls.getObject());
// ---------- Movement Variables ----------
const move = {
forward: false,
backward: false,
left: false,
right: false
};
const velocity = new THREE.Vector3();
const direction = new THREE.Vector3();
const speed = 400.0; // Units per second
// ---------- Event Listeners for Key Presses ----------
const onKeyDown = function (event) {
switch (event.code) {
case 'KeyW':
case 'ArrowUp':
move.forward = true;
break;
case 'KeyA':
case 'ArrowLeft':
move.left = true;
break;
case 'KeyS':
case 'ArrowDown':
move.backward = true;
break;
case 'KeyD':
case 'ArrowRight':
move.right = true;
break;
}
};
const onKeyUp = function (event) {
switch (event.code) {
case 'KeyW':
case 'ArrowUp':
move.forward = false;
break;
case 'KeyA':
case 'ArrowLeft':
move.left = false;
break;
case 'KeyS':
case 'ArrowDown':
move.backward = false;
break;
case 'KeyD':
case 'ArrowRight':
move.right = false;
break;
}
};
window.addEventListener('keydown', onKeyDown, false);
window.addEventListener('keyup', onKeyUp, false);
// ---------- Bullet Array ----------
const bullets = [];
const bulletSpeed = 1000; // Units per second
const bulletGeometry = new THREE.SphereGeometry(0.5, 8, 8);
const bulletMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 }); // Yellow bullets
// ---------- Shooting Mechanism ----------
const shoot = () => {
const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
bullet.position.copy(camera.position);
// Calculate direction
const vector = new THREE.Vector3(0, 0, -1);
vector.applyQuaternion(camera.quaternion);
bullet.velocity = vector.clone().multiplyScalar(bulletSpeed * deltaTime);
scene.add(bullet);
bullets.push(bullet);
// Trigger recoil animation
recoil();
};
let deltaTime = 0; // Time between frames
window.addEventListener('mousedown', (event) => {
if (event.button === 0 && controls.isLocked === true) { // Left mouse button
shoot();
}
}, false);
// ---------- Handle Window Resize ----------
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}, false);
// ---------- Gun Setup ----------
// Create a simple gun using basic geometries
const gun = new THREE.Group();
// Gun Base
const gunBaseGeometry = new THREE.BoxGeometry(1, 0.5, 3);
const gunBaseMaterial = new THREE.MeshPhongMaterial({ color: 0x333333 });
const gunBase = new THREE.Mesh(gunBaseGeometry, gunBaseMaterial);
gunBase.position.set(0, -0.5, -1.5);
gun.add(gunBase);
// Gun Barrel
const gunBarrelGeometry = new THREE.CylinderGeometry(0.1, 0.1, 2, 8);
const gunBarrelMaterial = new THREE.MeshPhongMaterial({ color: 0x555555 });
const gunBarrel = new THREE.Mesh(gunBarrelGeometry, gunBarrelMaterial);
gunBarrel.rotation.x = Math.PI / 2;
gunBarrel.position.set(0, -0.2, -2);
gun.add(gunBarrel);
// Optional: Add a sight
const sightGeometry = new THREE.BoxGeometry(0.1, 0.1, 0.5);
const sightMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000 });
const sight = new THREE.Mesh(sightGeometry, sightMaterial);
sight.position.set(0, 0, -2.6);
gun.add(sight);
// Position the gun in front of the camera
gun.position.set(0.5, -1, -2); // Adjust as needed for better appearance
camera.add(gun); // Add the gun to the camera's hierarchy
// Enable shadows for gun parts
gunBase.castShadow = true;
gunBarrel.castShadow = true;
sight.castShadow = true;
gunBase.receiveShadow = true;
gunBarrel.receiveShadow = true;
sight.receiveShadow = true;
// ---------- Recoil Animation ----------
let isRecoiling = false;
const recoilDistance = 0.1; // How much the gun moves back
const recoilSpeed = 0.5; // Speed of recoil
const maxRecoil = 0.1; // Maximum recoil displacement
const originalGunPosition = new THREE.Vector3(0.5, -1, -2);
const recoil = () => {
if (!isRecoiling) {
isRecoiling = true;
}
};
// ---------- Animation Loop ----------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
deltaTime = clock.getDelta();
// Update Velocity Based on Movement
velocity.x -= velocity.x * 10.0 * deltaTime;
velocity.z -= velocity.z * 10.0 * deltaTime;
direction.z = Number(move.forward) - Number(move.backward);
direction.x = Number(move.right) - Number(move.left);
direction.normalize(); // this ensures consistent movements in all directions
if (move.forward || move.backward) velocity.z -= direction.z * speed * deltaTime;
if (move.left || move.right) velocity.x -= direction.x * speed * deltaTime;
controls.moveRight(- velocity.x * deltaTime);
controls.moveForward(- velocity.z * deltaTime);
// Prevent camera from going below ground
if (controls.getObject().position.y < 10) {
controls.getObject().position.y = 10;
velocity.y = 0;
}
// Update Bullets
for (let i = 0; i < bullets.length; i++) {
const bullet = bullets[i];
bullet.position.add(bullet.velocity);
// Collision Detection with Targets
for (let j = 0; j < targets.length; j++) {
const target = targets[j];
const distance = bullet.position.distanceTo(target.position);
if (distance < 10) { // Assuming target radius ~10
// Remove target and bullet
scene.remove(target);
targets.splice(j, 1);
scene.remove(bullet);
bullets.splice(i, 1);
i--;
break;
}
}
// Remove bullets that are too far away
const distanceFromCamera = bullet.position.distanceTo(camera.position);
if (distanceFromCamera > 1000) {
scene.remove(bullet);
bullets.splice(i, 1);
i--;
}
}
// Handle Recoil Animation
if (isRecoiling) {
// Move the gun back slightly
gun.position.z += recoilSpeed * deltaTime;
if (gun.position.z > originalGunPosition.z + recoilDistance) {
isRecoiling = false;
}
} else {
// Return the gun to its original position smoothly
gun.position.z += (originalGunPosition.z - gun.position.z) * recoilSpeed * deltaTime;
gun.position.x += (originalGunPosition.x - gun.position.x) * recoilSpeed * deltaTime;
gun.position.y += (originalGunPosition.y - gun.position.y) * recoilSpeed * deltaTime;
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
Gun Creation:
THREE.Group() for easier manipulation.// ---------- Gun Setup ----------
// Create a simple gun using basic geometries
const gun = new THREE.Group();
// Gun Base
const gunBaseGeometry = new THREE.BoxGeometry(1, 0.5, 3);
const gunBaseMaterial = new THREE.MeshPhongMaterial({ color: 0x333333 });
const gunBase = new THREE.Mesh(gunBaseGeometry, gunBaseMaterial);
gunBase.position.set(0, -0.5, -1.5);
gun.add(gunBase);
// Gun Barrel
const gunBarrelGeometry = new THREE.CylinderGeometry(0.1, 0.1, 2, 8);
const gunBarrelMaterial = new THREE.MeshPhongMaterial({ color: 0x555555 });
const gunBarrel = new THREE.Mesh(gunBarrelGeometry, gunBarrelMaterial);
gunBarrel.rotation.x = Math.PI / 2;
gunBarrel.position.set(0, -0.2, -2);
gun.add(gunBarrel);
// Optional: Add a sight
const sightGeometry = new THREE.BoxGeometry(0.1, 0.1, 0.5);
const sightMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000 });
const sight = new THREE.Mesh(sightGeometry, sightMaterial);
sight.position.set(0, 0, -2.6);
gun.add(sight);
// Position the gun in front of the camera
gun.position.set(0.5, -1, -2); // Adjust as needed for better appearance
camera.add(gun); // Add the gun to the camera's hierarchy
// Enable shadows for gun parts
gunBase.castShadow = true;
gunBarrel.castShadow = true;
sight.castShadow = true;
gunBase.receiveShadow = true;
gunBarrel.receiveShadow = true;
sight.receiveShadow = true;
Using 3D Models: For a more realistic gun, consider using a 3D model loaded via GLTFLoader. This approach allows you to use detailed models from online repositories like Poly Pizza or Sketchfab.
import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/three@0.152.0/examples/jsm/loaders/GLTFLoader.js';
const loader = new GLTFLoader();
loader.load('path_to_gun_model/scene.gltf', function(gltf) {
const gunModel = gltf.scene;
gunModel.scale.set(0.5, 0.5, 0.5); // Adjust scale as needed
gun.add(gunModel);
}, undefined, function(error) {
console.error(error);
});
Adding Animations: Implement firing animations like moving parts (e.g., sliding magazine) or muzzle flashes to enhance visual feedback.
Sound Effects: Incorporate shooting sounds using the Audio API to make shooting more immersive.
const listener = new THREE.AudioListener();
camera.add(listener);
const gunShotSound = new THREE.Audio(listener);
const audioLoader = new THREE.AudioLoader();
audioLoader.load('sounds/gunshot.mp3', function(buffer) {
gunShotSound.setBuffer(buffer);
gunShotSound.setVolume(0.5);
});
const shoot = () => {
// ... existing shooting code ...
// Play shooting sound
gunShotSound.play();
// Trigger recoil animation
recoil();
};
Improving Recoil Mechanics: Make the recoil more dynamic by incorporating randomness or varying magnitudes based on factors like shot type or player stance.
The above implementation provides a foundational gun model and basic recoil mechanics for your FPS game. Depending on your game's complexity and desired realism, you can further enhance the gun's appearance, add detailed animations, and integrate sound effects. Utilizing 3D models from external sources can significantly improve the visual quality and realism of the gun, making your game more engaging.
Feel free to experiment with the gun's positioning, scaling, and animations to best suit your game's aesthetic and mechanics. Happy coding!
Not yet included in a published release.
Attaching the Gun to the Camera:
camera.add(gun); // Add the gun to the camera's hierarchy
Positioning the Gun:
x = 0.5), below the center (y = -1), and in front of the camera (z = -2). Adjust these values as needed to achieve the desired appearance.gun.position.set(0.5, -1, -2); // Adjust as needed for better appearance
Recoil Animation:
// ---------- Recoil Animation ----------
let isRecoiling = false;
const recoilDistance = 0.1; // How much the gun moves back
const recoilSpeed = 0.5; // Speed of recoil
const maxRecoil = 0.1; // Maximum recoil displacement
const originalGunPosition = new THREE.Vector3(0.5, -1, -2);
const recoil = () => {
if (!isRecoiling) {
isRecoiling = true;
}
};
// Inside the animate loop
// Handle Recoil Animation
if (isRecoiling) {
// Move the gun back slightly
gun.position.z += recoilSpeed * deltaTime;
if (gun.position.z > originalGunPosition.z + recoilDistance) {
isRecoiling = false;
}
} else {
// Return the gun to its original position smoothly
gun.position.z += (originalGunPosition.z - gun.position.z) * recoilSpeed * deltaTime;
gun.position.x += (originalGunPosition.x - gun.position.x) * recoilSpeed * deltaTime;
gun.position.y += (originalGunPosition.y - gun.position.y) * recoilSpeed * deltaTime;
}
Synchronizing Recoil with Shooting:
recoil() function is called whenever a shot is fired to trigger the recoil animation.// Inside the shoot function
shoot = () => {
// ... existing shooting code ...
// Trigger recoil animation
recoil();
};