Blast World 3D
by BoldPenguin144204 lines58.7 KB🛠️ Three.js (3D graphics)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Blast World 3D</title>
<style>
*{
box-sizing:border-box;
-webkit-tap-highlight-color:transparent;
}
html,body{
margin:0;
width:100%;
height:100%;
overflow:hidden;
background:#05070a;
font-family:Arial,sans-serif;
touch-action:none;
overscroll-behavior:none;
}
body{
user-select:none;
-webkit-user-select:none;
}
button,input{
font-family:Arial,sans-serif;
}
button{
cursor:pointer;
touch-action:manipulation;
}
canvas{
position:fixed;
inset:0;
width:100%;
height:100%;
display:block;
touch-action:none;
}
.screen{
position:fixed;
inset:0;
z-index:1000;
display:none;
align-items:center;
justify-content:center;
padding:12px;
background:
radial-gradient(circle at 50% 20%,rgba(120,220,255,.25),transparent 35%),
linear-gradient(135deg,#172b45,#203d2c 50%,#101923);
touch-action:auto;
}
.screen.active{
display:flex;
}
.panel{
width:94%;
max-width:650px;
max-height:94vh;
overflow:auto;
padding:20px;
color:#fff;
text-align:center;
background:linear-gradient(145deg,#3d4650,#20252b);
border:3px solid #111;
border-radius:18px;
box-shadow:
0 18px 0 #080b0e,
0 28px 45px rgba(0,0,0,.65),
inset 0 1px rgba(255,255,255,.2);
}
h1{
font-size:38px;
margin:5px 0 20px;
text-shadow:0 3px 0 #000,0 6px 15px rgba(0,0,0,.7);
}
h2{
margin:8px;
}
p{
line-height:1.4;
}
.menuBtn,
.btn{
display:block;
width:94%;
min-height:58px;
margin:14px auto;
border:3px solid #0b0d10;
border-radius:12px;
box-shadow:
0 6px 0 #090b0d,
inset 0 1px rgba(255,255,255,.3);
background:linear-gradient(#777,#454545);
color:#fff;
font-size:19px;
font-weight:bold;
}
.menuBtn:active,
.btn:active{
transform:translateY(5px);
box-shadow:0 1px 0 #111;
}
.start{
background:linear-gradient(#66c653,#2f7f30);
}
.friendPlay{
background:linear-gradient(#29b6e6,#17658c);
}
.friends{
background:linear-gradient(#8b70e4,#55419b);
}
.card{
background:linear-gradient(145deg,#505a63,#30363b);
border:2px solid #101214;
border-radius:12px;
padding:12px;
margin:12px 0;
box-shadow:
inset 0 1px rgba(255,255,255,.12),
0 5px 12px rgba(0,0,0,.25);
}
.card button{
width:100%;
min-height:50px;
background:linear-gradient(#858585,#505050);
color:#fff;
border:2px solid #111;
border-radius:9px;
padding:12px;
margin:5px 0;
font-weight:bold;
font-size:16px;
}
.diff{
display:block;
width:95%;
margin:12px auto;
padding:15px;
color:white;
text-align:left;
background:linear-gradient(145deg,#555,#333);
border:3px solid #111;
border-radius:12px;
box-shadow:0 5px 0 #111;
}
.easy{border-left:14px solid #25d83d}
.medium{border-left:14px solid #e5dc27}
.hard{border-left:14px solid #ed7b22}
.impossible{border-left:14px solid #e52c2c}
input{
width:90%;
padding:14px;
border:3px solid #111;
border-radius:10px;
background:#eee;
color:#111;
font-size:19px;
text-align:center;
}
.friendItem{
background:linear-gradient(145deg,#454b51,#292d31);
border:2px solid #111;
border-radius:9px;
padding:12px;
margin:8px 0;
text-align:left;
}
.friendItem button{
width:100%;
margin-top:8px;
min-height:45px;
border:2px solid #111;
border-radius:8px;
background:linear-gradient(#438edb,#275b91);
color:#fff;
font-weight:bold;
}
.friendSelected{
border:3px solid #39ff65;
}
.gunChoice{
width:100%;
margin:6px 0;
padding:12px;
border:2px solid #111;
border-radius:9px;
background:#555;
color:#fff;
font-weight:bold;
}
.shopOwned{
background:linear-gradient(#35ad55,#216f35)!important;
}
.bought,
.priceOK{
color:#65ff65!important;
font-weight:bold;
}
.priceBad{
color:#ff3333!important;
font-weight:bold;
}
#hud{
position:fixed;
left:8px;
top:8px;
z-index:40;
color:#fff;
font-weight:bold;
font-size:13px;
line-height:1.2;
text-shadow:2px 2px 4px #000;
display:none;
pointer-events:none;
padding:6px 8px;
border-radius:8px;
background:rgba(0,0,0,.45);
border:1px solid rgba(255,255,255,.15);
}
.healthOuter{
width:110px;
height:10px;
background:#171717;
border:1px solid #080808;
border-radius:4px;
margin:2px 0 4px;
overflow:hidden;
}
#healthBar{
height:100%;
width:100%;
background:linear-gradient(#65ff69,#19a52b);
}
#crosshair{
position:fixed;
left:50%;
top:50%;
transform:translate(-50%,-50%);
z-index:35;
color:#fff;
font-size:34px;
font-weight:bold;
text-shadow:0 0 5px #000,2px 2px #000;
display:none;
pointer-events:none;
}
#ammo{
position:fixed;
right:18px;
bottom:130px;
z-index:45;
color:#fff;
font-size:23px;
font-weight:bold;
text-shadow:2px 2px 5px #000;
display:none;
pointer-events:none;
padding:8px 12px;
border-radius:10px;
background:rgba(0,0,0,.35);
}
#weaponName{
position:fixed;
right:18px;
bottom:94px;
z-index:45;
color:#fff;
font-weight:bold;
text-shadow:2px 2px 5px #000;
display:none;
pointer-events:none;
}
#upgradeText{
position:fixed;
right:18px;
top:85px;
z-index:45;
color:#ffe800;
font-weight:bold;
text-shadow:2px 2px 5px #000;
display:none;
pointer-events:none;
}
#joystick{
position:fixed;
left:20px;
bottom:28px;
width:135px;
height:135px;
border-radius:50%;
background:radial-gradient(circle,rgba(255,255,255,.13),rgba(0,0,0,.6));
border:3px solid rgba(255,255,255,.65);
box-shadow:
0 8px 25px rgba(0,0,0,.5),
inset 0 0 20px rgba(255,255,255,.1);
z-index:300;
display:none;
touch-action:none;
}
#stick{
position:absolute;
left:50%;
top:50%;
width:57px;
height:57px;
transform:translate(-50%,-50%);
border-radius:50%;
background:radial-gradient(circle at 35% 30%,#fff,#aaa);
box-shadow:0 5px 15px #000;
pointer-events:none;
}
#cameraArea{
position:fixed;
right:0;
top:0;
width:72%;
height:100%;
z-index:90;
display:none;
touch-action:none;
user-select:none;
}
#fireButton{
position:fixed;
right:25px;
bottom:35px;
width:102px;
height:102px;
border-radius:50%;
background:radial-gradient(circle at 35% 25%,#ff6767,#a70f0f 70%);
color:white;
border:5px solid white;
box-shadow:0 7px 20px rgba(0,0,0,.6);
z-index:300;
font-weight:bold;
display:none;
touch-action:none;
}
#gameMessage{
position:fixed;
left:0;
bottom:180px;
width:100%;
z-index:310;
text-align:center;
color:#fff;
font-size:21px;
font-weight:bold;
text-shadow:2px 2px 5px #000;
pointer-events:none;
}
#pauseButton,
#soundButton{
position:fixed;
top:10px;
z-index:400;
display:none;
background:linear-gradient(#666,#333);
color:#fff;
border:2px solid #111;
border-radius:8px;
padding:9px 14px;
font-weight:bold;
box-shadow:0 4px 0 #111;
}
#pauseButton{right:110px}
#soundButton{right:10px}
@media(max-width:600px){
.panel{
padding:12px;
}
h1{
font-size:30px;
}
#joystick{
left:12px;
bottom:22px;
}
#fireButton{
right:15px;
bottom:25px;
}
#cameraArea{
width:68%;
}
}
</style>
</head>
<body>
<div id="game"></div>
<!-- MAIN MENU -->
<div id="mainMenu" class="screen active">
<div class="panel">
<h1>⛏️ BLAST WORLD 3D</h1>
<button class="menuBtn start" id="playBtn">
▶ START GAME
</button>
<button class="menuBtn" id="difficultyBtn">
⚔️ DIFFICULTY
</button>
<button class="menuBtn" id="nameBtn">
✏️ CHANGE NAME
</button>
<button class="menuBtn" id="tutorialBtn">
📖 TUTORIAL
</button>
<button class="menuBtn" id="shopBtn">
🛒 SHOP
</button>
<button class="menuBtn friends" id="friendsBtn">
👥 FRIENDS
</button>
<!-- NEW SEPARATE FRIEND PLAY BUTTON -->
<button class="menuBtn friendPlay" id="playFriendBtn">
🎮 PLAY WITH FRIEND
</button>
<p>
Progress automatically saves on this device.
</p>
<p>
Player: <b id="menuPlayerName">Player</b>
</p>
</div>
</div>
<!-- ORIENTATION -->
<div id="orientationMenu" class="screen">
<div class="panel">
<h1>📱 SCREEN MODE</h1>
<button class="menuBtn" id="verticalBtn">
📱 PLAY VERTICALLY
</button>
<button class="menuBtn" id="horizontalBtn">
🖥️ PLAY HORIZONTALLY
</button>
<button class="btn" id="orientationBack">
BACK
</button>
</div>
</div>
<!-- MAP -->
<div id="mapMenu" class="screen">
<div class="panel">
<h1>🗺️ MAP</h1>
<button class="menuBtn" data-map="beach">
🏖️ BEACH
</button>
<button class="menuBtn" data-map="city">
🏙️ BLOCK CITY
</button>
<button class="menuBtn" data-map="desert">
🏜️ DESERT
</button>
<button class="btn" id="mapBack">
BACK
</button>
</div>
</div>
<!-- DIFFICULTY -->
<div id="difficultyMenu" class="screen">
<div class="panel">
<h1>⚔️ DIFFICULTY</h1>
<button class="diff easy" data-difficulty="easy">
<h2>🟢 EASY</h2>
Enemies chase you slowly.
</button>
<button class="diff medium" data-difficulty="medium">
<h2>🟡 MEDIUM</h2>
Enemies are almost as fast as you.
</button>
<button class="diff hard" data-difficulty="hard">
<h2>🟠 HARD</h2>
Enemies are very fast.
</button>
<button class="diff impossible" data-difficulty="impossible">
<h2>🔴 IMPOSSIBLE</h2>
Enemies are extremely fast and dangerous.
</button>
<button class="btn" id="difficultyBack">
BACK
</button>
</div>
</div>
<!-- NAME -->
<div id="nameMenu" class="screen">
<div class="panel">
<h1>✏️ CHANGE NAME</h1>
<input id="nameInput"
maxlength="18"
placeholder="Enter your name">
<button class="btn" id="saveName">
SAVE NAME
</button>
<button class="btn" id="nameBack">
BACK
</button>
</div>
</div>
<!-- TUTORIAL -->
<div id="tutorialMenu" class="screen">
<div class="panel">
<h1>📖 TUTORIAL</h1>
<div class="card">
<h2>🕹️ MOVE</h2>
<p>Use the left joystick or W A S D.</p>
</div>
<div class="card">
<h2>👀 LOOK</h2>
<p>
Drag the right side. Drag upward to look up,
just like Minecraft.
</p>
</div>
<div class="card">
<h2>🔫 SHOOT</h2>
<p>Press FIRE or E/SPACE.</p>
</div>
<div class="card">
<h2>🏃 BREAK ANKLES</h2>
<p>
Run toward an enemy and make a sharp turn.
Enemies chase your current position, so sharp
turns can make them overshoot.
</p>
</div>
<div class="card">
<h2>💥 ROCKETS</h2>
<p>Use the bazooka for explosive damage.</p>
</div>
<button class="btn" id="tutorialBack">
BACK
</button>
</div>
</div>
<!-- SHOP -->
<div id="shopMenu" class="screen">
<div class="panel">
<h1>🛒 SHOP</h1>
<h2 style="color:#48f04c">
$<span id="shopMoney">1,000,000</span>
</h2>
<div class="card">
<h2>🏃 SPEED</h2>
<p>
Speed Level:
<b id="speedLevel">1</b>
</p>
<p>
Current Speed:
<b id="speedValue">0.18</b>
</p>
<!-- CHANGED TO $1 -->
<button id="speedUpgradeBtn">
🏃 UPGRADE SPEED — $1
</button>
<p>
Unlimited upgrades. Every upgrade costs only $1.
</p>
</div>
<div class="card">
<h2>🔫 WEAPONS</h2>
<button data-shop-gun="pistol">
PISTOL<br>
<span class="gunPrice">FREE</span>
</button>
<button data-shop-gun="smg">
SMG<br>
<span class="gunPrice">$75K</span>
</button>
<button data-shop-gun="shotgun">
SHOTGUN<br>
<span class="gunPrice">$150K</span>
</button>
<button data-shop-gun="rifle">
RIFLE<br>
<span class="gunPrice">$300K</span>
</button>
<button data-shop-gun="laser">
LASER<br>
<span class="gunPrice">$600K</span>
</button>
<button data-shop-gun="bazooka">
🚀 BAZOOKA<br>
<span class="gunPrice">$500K</span>
</button>
<p>
Current:
<b id="currentGun">PISTOL</b>
</p>
</div>
<div class="card">
<h2>💪 DAMAGE</h2>
<p>
Level <span id="damageLevel">1</span>
</p>
<button data-upgrade="damage">
UPGRADE DAMAGE $25K
</button>
</div>
<div class="card">
<h2>💥 KNOCKBACK</h2>
<p>
Level <span id="blastLevel">1</span>
</p>
<button data-upgrade="blast">
UPGRADE KNOCKBACK $40K
</button>
</div>
<button class="btn" id="shopBack">
BACK
</button>
</div>
</div>
<!-- FRIENDS -->
<div id="friendsMenu" class="screen">
<div class="panel">
<h1>👥 FRIENDS</h1>
<div class="card">
<h2>🤝 YOUR FRIENDS</h2>
<div id="friendsList">
No friends yet.
</div>
</div>
<input
id="friendNameInput"
maxlength="18"
placeholder="Enter friend name">
<button class="menuBtn friends" id="addFriendBtn">
➕ ADD FRIEND
</button>
<button class="btn" id="friendsBack">
BACK
</button>
</div>
</div>
<!-- PLAY WITH FRIEND -->
<div id="playFriendMenu" class="screen">
<div class="panel">
<h1>🎮 PLAY WITH FRIEND</h1>
<div class="card">
<h2>👥 SELECT FRIEND</h2>
<div id="playFriendList">
No friends yet.
</div>
</div>
<div class="card">
<h2>🌐 FRIEND GAME</h2>
<p id="selectedFriendText">
Select a friend to play with.
</p>
<p>
For real online multiplayer, this screen
will connect to the multiplayer server.
</p>
</div>
<button
class="menuBtn friendPlay"
id="hostFriendGameBtn">
🎮 CREATE FRIEND GAME
</button>
<button class="btn" id="playFriendBack">
BACK
</button>
</div>
</div>
<!-- FRIEND GAME CREATED -->
<div id="friendRoomMenu" class="screen">
<div class="panel">
<h1>🎮 FRIEND GAME</h1>
<div class="card">
<h2>🔗 GAME ROOM</h2>
<p>
Room Code
</p>
<h1 id="roomCode"
style="color:#49eaff">
------
</h1>
<p>
Give this room code to your friend.
</p>
</div>
<div class="card">
<h2>👥 PLAYERS</h2>
<div id="roomPlayers">
</div>
</div>
<button class="menuBtn start" id="startFriendGameBtn">
▶ START GAME
</button>
<button class="btn" id="friendRoomBack">
BACK
</button>
</div>
</div>
<!-- PAUSE -->
<div id="pauseScreen" class="screen">
<div class="panel">
<h1>⏸ PAUSED</h1>
<button class="btn" id="resumeButton">
▶ RESUME
</button>
<button class="btn" id="pauseMenuButton">
MAIN MENU
</button>
</div>
</div>
<!-- GAME OVER -->
<div id="gameOver" class="screen">
<div class="panel">
<h1 style="color:#ff3333">
YOU DIED
</h1>
<h2>
Score: <span id="scoreText">0</span>
</h2>
<button class="btn" id="againBtn">
PLAY AGAIN
</button>
<button class="btn" id="gameOverMenuBtn">
MAIN MENU
</button>
</div>
</div>
<!-- HUD -->
<div id="hud">
❤️ HEALTH
<div class="healthOuter">
<div id="healthBar"></div>
</div>
💰 $<span id="moneyText">1,000,000</span>
<br>
👤 <span id="playerNameHUD">Player</span>
<br>
🗺️ <span id="mapText">BEACH</span>
<br>
⚔️ <span id="difficultyText">MEDIUM</span>
</div>
<div id="crosshair">+</div>
<div id="ammo">
🔫 <span id="ammoText">30</span>/
<span id="maxAmmo">30</span>
</div>
<div id="weaponName">
PISTOL
</div>
<div id="upgradeText">
DAMAGE x1 | BLAST x1 | SPEED x1
</div>
<div id="joystick">
<div id="stick"></div>
</div>
<div id="cameraArea"></div>
<button id="fireButton">
FIRE
</button>
<div id="gameMessage"></div>
<button id="pauseButton">
⏸ PAUSE
</button>
<button id="soundButton">
🔊 SOUND
</button>
<script src="https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js"></script>
<script>
"use strict";
/* =========================================================
GAME STATE
========================================================= */
let scene;
let camera;
let renderer;
let gunGroup;
let running=false;
let paused=false;
let reloading=false;
let reloadTimer=null;
let currentMap="beach";
let currentDifficulty="medium";
let orientation="portrait";
let playerName="Player";
let health=100;
let ammo=30;
let money=1000000;
let score=0;
let damageLevel=1;
let blastLevel=1;
let speedLevel=1;
let currentGun="pistol";
let soundEnabled=true;
let friends=[];
let selectedFriend="";
let roomCode="";
let ownedGuns={
pistol:true,
smg:false,
shotgun:false,
rifle:false,
laser:false,
bazooka:false
};
let enemies=[];
let worldObjects=[];
let bullets=[];
let rockets=[];
let joyX=0;
let joyY=0;
let joystickPointer=null;
let cameraPointer=null;
let lastCameraX=0;
let lastCameraY=0;
let lastShot=0;
const MAP_SIZE=260;
const EDGE=MAP_SIZE/2;
const BASE_PLAYER_SPEED=.18;
/*
SPEED UPGRADE IS NOW $1.
Every level adds .01 speed.
*/
const SPEED_UPGRADE=.01;
const player={
x:0,
y:1.7,
z:0,
yaw:0,
pitch:0
};
const keys={};
/* =========================================================
WEAPONS
========================================================= */
const guns={
pistol:{
name:"Pistol",
damage:35,
rate:450,
ammo:30,
color:0xffaa22,
knockback:.18,
bulletSpeed:3
},
smg:{
name:"SMG",
damage:42,
rate:150,
ammo:40,
color:0x44bbff,
knockback:.20,
bulletSpeed:3.2
},
shotgun:{
name:"Shotgun",
damage:110,
rate:800,
ammo:8,
color:0xff5500,
knockback:.75,
bulletSpeed:2.7
},
rifle:{
name:"Assault Rifle",
damage:75,
rate:120,
ammo:30,
color:0xffff00,
knockback:.32,
bulletSpeed:3.9
},
laser:{
name:"Laser Gun",
damage:150,
rate:100,
ammo:25,
color:0xff00ff,
knockback:.42,
bulletSpeed:5
},
bazooka:{
name:"Bazooka",
damage:300,
rate:1200,
ammo:5,
color:0xff3300,
knockback:1.8,
bulletSpeed:1.7
}
};
const weaponPrices={
pistol:0,
smg:75000,
shotgun:150000,
rifle:300000,
laser:600000,
bazooka:500000
};
/* =========================================================
DIFFICULTY
========================================================= */
const difficulty={
easy:{
count:8,
speed:.115,
damage:3,
attackDelay:900,
hp:80
},
medium:{
count:12,
speed:.145,
damage:7,
attackDelay:750,
hp:100
},
hard:{
count:16,
speed:.165,
damage:12,
attackDelay:650,
hp:150
},
impossible:{
count:22,
speed:.18,
damage:20,
attackDelay:550,
hp:200
}
};
/* =========================================================
HELPERS
========================================================= */
function $(id){
return document.getElementById(id);
}
function show(id){
document
.querySelectorAll(".screen")
.forEach(s=>s.classList.remove("active"));
const el=$(id);
if(el)
el.classList.add("active");
}
function rand(min,max){
return min+Math.random()*(max-min);
}
function escapeHTML(text){
return String(text)
.replace(/&/g,"&")
.replace(/</g,"<")
.replace(/>/g,">")
.replace(/"/g,""")
.replace(/'/g,"'");
}
function message(text){
$("gameMessage").textContent=text;
setTimeout(()=>{
if($("gameMessage").textContent===text)
$("gameMessage").textContent="";
},1200);
}
/* =========================================================
SAVE / LOAD
========================================================= */
const SAVE_KEY="blastWorld3D_save_v4";
function saveGameData(){
try{
localStorage.setItem(
SAVE_KEY,
JSON.stringify({
ownedGuns,
money,
currentGun,
damageLevel,
blastLevel,
speedLevel,
playerName,
friends,
currentMap,
currentDifficulty
})
);
}catch(e){
console.warn(
"Could not save game.",
e
);
}
}
function loadGameData(){
try{
const raw=
localStorage.getItem(SAVE_KEY);
if(!raw)
return;
const data=
JSON.parse(raw);
if(data.ownedGuns){
ownedGuns={
...ownedGuns,
...data.ownedGuns
};
}
if(typeof data.money==="number")
money=Math.max(
0,
data.money
);
if(typeof data.damageLevel==="number")
damageLevel=Math.max(
1,
Math.floor(data.damageLevel)
);
if(typeof data.blastLevel==="number")
blastLevel=Math.max(
1,
Math.floor(data.blastLevel)
);
if(typeof data.speedLevel==="number")
speedLevel=Math.max(
1,
Math.floor(data.speedLevel)
);
if(
typeof data.playerName==="string" &&
data.playerName.trim()
){
playerName=
data.playerName
.trim()
.substring(0,18);
}
if(Array.isArray(data.friends)){
friends=
data.friends
.filter(x=>typeof x==="string")
.map(x=>x.substring(0,18));
}
if(
["beach","city","desert"]
.includes(data.currentMap)
)
currentMap=data.currentMap;
if(difficulty[data.currentDifficulty])
currentDifficulty=
data.currentDifficulty;
if(
typeof data.currentGun==="string" &&
guns[data.currentGun] &&
ownedGuns[data.currentGun]
)
currentGun=data.currentGun;
}catch(e){
console.warn(
"Save data was invalid.",
e
);
}
}
/* =========================================================
MAIN MENU
========================================================= */
$("playBtn").onclick=()=>{
show("orientationMenu");
};
$("playFriendBtn").onclick=()=>{
renderPlayFriendList();
show("playFriendMenu");
};
$("difficultyBtn").onclick=()=>{
show("difficultyMenu");
};
$("nameBtn").onclick=()=>{
$("nameInput").value=
playerName;
show("nameMenu");
};
$("tutorialBtn").onclick=()=>{
show("tutorialMenu");
};
$("shopBtn").onclick=()=>{
updateShop();
show("shopMenu");
};
$("friendsBtn").onclick=()=>{
renderFriends();
show("friendsMenu");
};
/* =========================================================
ORIENTATION
========================================================= */
$("orientationBack").onclick=()=>{
show("mainMenu");
};
$("verticalBtn").onclick=()=>{
orientation="portrait";
show("mapMenu");
};
$("horizontalBtn").onclick=async()=>{
orientation="landscape";
show("mapMenu");
try{
if(document.documentElement.requestFullscreen)
await document.documentElement.requestFullscreen();
}catch(e){}
try{
if(
screen.orientation &&
screen.orientation.lock
)
await screen.orientation.lock("landscape");
}catch(e){}
};
/* =========================================================
MAP
========================================================= */
$("mapBack").onclick=()=>{
show("orientationMenu");
};
document
.querySelectorAll("[data-map]")
.forEach(button=>{
button.onclick=()=>{
currentMap=
button.dataset.map;
saveGameData();
show("difficultyMenu");
};
});
/* =========================================================
DIFFICULTY
========================================================= */
$("difficultyBack").onclick=()=>{
show("mainMenu");
};
document
.querySelectorAll("[data-difficulty]")
.forEach(button=>{
button.onclick=()=>{
currentDifficulty=
button.dataset.difficulty;
saveGameData();
startGame();
};
});
/* =========================================================
NAME
========================================================= */
$("nameBack").onclick=()=>{
show("mainMenu");
};
$("saveName").onclick=()=>{
let name=
$("nameInput")
.value
.trim();
if(!name)
name="Player";
playerName=
name.substring(0,18);
$("menuPlayerName").textContent=
playerName;
$("playerNameHUD").textContent=
playerName;
saveGameData();
show("mainMenu");
};
/* =========================================================
TUTORIAL
========================================================= */
$("tutorialBack").onclick=()=>{
show("mainMenu");
};
/* =========================================================
FRIENDS
========================================================= */
function renderFriends(){
const box=$("friendsList");
box.innerHTML="";
if(!friends.length){
box.innerHTML=
"<p>No friends yet.</p>";
return;
}
friends.forEach((name,index)=>{
const div=
document.createElement("div");
div.className="friendItem";
div.innerHTML=`
👤 <b>${escapeHTML(name)}</b>
<br>
<small style="color:#58ff72">
🟢 FRIEND
</small>
<button data-remove="${index}">
❌ REMOVE FRIEND
</button>
`;
box.appendChild(div);
});
box
.querySelectorAll("[data-remove]")
.forEach(button=>{
button.onclick=()=>{
const index=
Number(
button.dataset.remove
);
friends.splice(
index,
1
);
if(
selectedFriend &&
!friends.includes(
selectedFriend
)
){
selectedFriend="";
}
saveGameData();
renderFriends();
message(
"👥 FRIEND REMOVED"
);
};
});
}
$("addFriendBtn").onclick=()=>{
const input=
$("friendNameInput");
const name=
input.value.trim();
if(!name){
alert(
"Enter a friend's name."
);
return;
}
if(
name.toLowerCase()===
playerName.toLowerCase()
){
alert(
"You cannot add yourself."
);
return;
}
if(
friends.some(
x=>
x.toLowerCase()===
name.toLowerCase()
)
){
alert(
"That friend is already added."
);
return;
}
friends.push(
name.substring(0,18)
);
input.value="";
saveGameData();
renderFriends();
message(
"👥 FRIEND ADDED!"
);
};
$("friendsBack").onclick=()=>{
show("mainMenu");
};
/* =========================================================
PLAY WITH FRIEND MENU
========================================================= */
function renderPlayFriendList(){
const box=
$("playFriendList");
box.innerHTML="";
if(!friends.length){
box.innerHTML=`
<p>
You don't have any friends yet.
</p>
<button
class="menuBtn friends"
id="goAddFriend"
>
➕ ADD FRIEND
</button>
`;
$("goAddFriend").onclick=()=>{
show("friendsMenu");
};
$("selectedFriendText").textContent=
"Add a friend first.";
return;
}
friends.forEach(name=>{
const button=
document.createElement("button");
button.className=
"menuBtn";
if(
selectedFriend===name
)
button.classList.add(
"friendSelected"
);
button.textContent=
"👤 "+name;
button.onclick=()=>{
selectedFriend=name;
renderPlayFriendList();
message(
name+
" SELECTED"
);
};
box.appendChild(button);
});
if(selectedFriend){
$("selectedFriendText").innerHTML=
"🎮 Ready to play with <b>"+
escapeHTML(selectedFriend)+
"</b>.";
}else{
$("selectedFriendText").textContent=
"Select a friend to play with.";
}
}
$("playFriendBack").onclick=()=>{
show("mainMenu");
};
$("hostFriendGameBtn").onclick=()=>{
if(!selectedFriend){
alert(
"Select a friend first."
);
return;
}
createFriendRoom();
};
function generateRoomCode(){
const chars=
"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let code="";
for(let i=0;i<6;i++){
code+=
chars[
Math.floor(
Math.random()*
chars.length
)
];
}
return code;
}
function createFriendRoom(){
roomCode=
generateRoomCode();
$("roomCode").textContent=
roomCode;
$("roomPlayers").innerHTML=`
<div class="friendItem">
👤 <b>${escapeHTML(playerName)}</b>
<br>
🟢 HOST
</div>
<div class="friendItem">
👤 <b>${escapeHTML(selectedFriend)}</b>
<br>
🟡 INVITED
</div>
`;
show("friendRoomMenu");
}
$("friendRoomBack").onclick=()=>{
show("playFriendMenu");
};
$("startFriendGameBtn").onclick=()=>{
/*
Currently starts the normal game locally.
To make this a true online 2-player game,
this button would send the room/player data
through WebSocket/WebRTC to another browser.
*/
startGame();
};
/* =========================================================
SHOP
========================================================= */
function updateShop(){
$("shopMoney").textContent=
money.toLocaleString();
$("currentGun").textContent=
guns[currentGun]
.name
.toUpperCase();
$("damageLevel").textContent=
damageLevel;
$("blastLevel").textContent=
blastLevel;
$("speedLevel").textContent=
speedLevel;
$("speedValue").textContent=
getPlayerSpeed().toFixed(2);
document
.querySelectorAll("[data-shop-gun]")
.forEach(button=>{
const gun=
button.dataset.shopGun;
const price=
weaponPrices[gun];
const span=
button.querySelector(
".gunPrice"
);
button.classList.remove(
"shopOwned"
);
if(gun==="pistol"){
span.textContent="FREE";
span.className=
"gunPrice bought";
button.classList.add(
"shopOwned"
);
return;
}
if(ownedGuns[gun]){
span.textContent="BOUGHT";
span.className=
"gunPrice bought";
button.classList.add(
"shopOwned"
);
return;
}
span.textContent=
"$"+
price.toLocaleString();
span.className=
money>=price
?"gunPrice priceOK"
:"gunPrice priceBad";
});
}
$("shopBack").onclick=()=>{
show("mainMenu");
};
/* =========================================================
SPEED UPGRADE — $1
========================================================= */
$("speedUpgradeBtn").onclick=()=>{
const price=1;
if(money<price){
message(
"❌ NOT ENOUGH MONEY!"
);
return;
}
money-=price;
speedLevel++;
saveGameData();
updateShop();
updateHUD();
message(
"🏃 SPEED LEVEL "+
speedLevel+
"!"
);
};
/* =========================================================
WEAPON PURCHASE
========================================================= */
document
.querySelectorAll("[data-shop-gun]")
.forEach(button=>{
button.onclick=()=>{
const gun=
button.dataset.shopGun;
const price=
weaponPrices[gun];
if(ownedGuns[gun]){
currentGun=gun;
ammo=
guns[gun].ammo;
saveGameData();
updateGunModel();
updateShop();
updateHUD();
message(
guns[gun]
.name
.toUpperCase()+
" EQUIPPED"
);
return;
}
if(money<price){
message(
"❌ NOT ENOUGH MONEY!"
);
return;
}
money-=price;
ownedGuns[gun]=true;
currentGun=gun;
ammo=
guns[gun].ammo;
saveGameData();
updateGunModel();
updateShop();
updateHUD();
message(
guns[gun]
.name
.toUpperCase()+
" BOUGHT!"
);
};
});
/* =========================================================
DAMAGE / BLAST UPGRADES
========================================================= */
document
.querySelectorAll("[data-upgrade]")
.forEach(button=>{
button.onclick=()=>{
const type=
button.dataset.upgrade;
const price=
type==="damage"
?25000
:40000;
if(money<price){
message(
"❌ NOT ENOUGH MONEY!"
);
return;
}
money-=price;
if(type==="damage")
damageLevel++;
else
blastLevel++;
saveGameData();
updateShop();
updateHUD();
message(
type==="damage"
?"💪 DAMAGE UPGRADED!"
:"💥 KNOCKBACK UPGRADED!"
);
};
});
/* =========================================================
THREE.JS
========================================================= */
function init3D(){
scene=
new THREE.Scene();
scene.background=
new THREE.Color(
0x6fc8ee
);
scene.fog=
new THREE.FogExp2(
0x8ccbe5,
.006
);
camera=
new THREE.PerspectiveCamera(
75,
innerWidth/innerHeight,
.05,
600
);
renderer=
new THREE.WebGLRenderer({
antialias:true,
powerPreference:
"high-performance"
});
renderer.setPixelRatio(
Math.min(
window.devicePixelRatio||1,
2
)
);
renderer.setSize(
innerWidth,
innerHeight
);
renderer.shadowMap.enabled=true;
renderer.outputColorSpace=
THREE.SRGBColorSpace;
renderer.toneMapping=
THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure=
1.15;
$("game").appendChild(
renderer.domElement
);
scene.add(camera);
scene.add(
new THREE.HemisphereLight(
0xbfefff,
0x27351f,
2.3
)
);
const sun=
new THREE.DirectionalLight(
0xffffff,
3.5
);
sun.position.set(
-80,
120,
60
);
sun.castShadow=true;
scene.add(sun);
createGun();
animate();
}
function mat(color){
return new THREE.MeshStandardMaterial({
color,
roughness:.75,
metalness:.05
});
}
function cube(
x,y,z,
w,h,d,
color
){
const mesh=
new THREE.Mesh(
new THREE.BoxGeometry(
w,h,d
),
mat(color)
);
mesh.position.set(
x,y,z
);
mesh.castShadow=true;
mesh.receiveShadow=true;
scene.add(mesh);
worldObjects.push(mesh);
return mesh;
}
/* =========================================================
MAP
========================================================= */
function clearWorld(){
worldObjects.forEach(o=>{
scene.remove(o);
if(o.geometry)
o.geometry.dispose();
if(o.material)
o.material.dispose();
});
enemies.forEach(e=>{
scene.remove(e.group);
});
bullets.forEach(b=>{
scene.remove(b.mesh);
});
rockets.forEach(r=>{
scene.remove(r.mesh);
});
worldObjects=[];
enemies=[];
bullets=[];
rockets=[];
}
function createMap(){
clearWorld();
cube(
0,-.5,0,
MAP_SIZE,
1,
MAP_SIZE,
currentMap==="desert"
?0xc99a55
:currentMap==="city"
?0x45494d
:0xd6b56d
);
if(currentMap==="beach")
createBeach();
if(currentMap==="city")
createCity();
if(currentMap==="desert")
createDesert();
}
function createBeach(){
const water=
new THREE.Mesh(
new THREE.PlaneGeometry(
MAP_SIZE,
45
),
new THREE.MeshStandardMaterial({
color:0x157db7,
roughness:.18,
metalness:.35
})
);
water.rotation.x=
-Math.PI/2;
water.position.set(
0,
-.42,
-108
);
scene.add(water);
worldObjects.push(water);
for(let i=0;i<25;i++){
const rock=
new THREE.Mesh(
new THREE.DodecahedronGeometry(
rand(.2,1),
0
),
mat(0x8b806e)
);
rock.position.set(
rand(-120,120),
0,
rand(-80,120)
);
rock.scale.y=.5;
rock.castShadow=true;
scene.add(rock);
worldObjects.push(rock);
}
}
function createBuilding(
x,z,w,d,color
){
cube(
x,4,z,
w,8,d,
color
);
cube(
x,8.2,z,
w+.4,.3,d+.4,
0x222222
);
}
function createCity(){
for(
let x=-100;
x<=100;
x+=50
){
for(
let z=-100;
z<=100;
z+=50
){
if(
Math.abs(x)<20 &&
Math.abs(z)<20
)
continue;
createBuilding(
x+rand(-4,4),
z+rand(-4,4),
rand(20,28),
rand(20,28),
[
0x68717b,
0x805d50,
0x536f82,
0x756356
][
Math.floor(
Math.random()*4
)
]
);
}
}
}
function createDesert(){
for(let i=0;i<35;i++){
const dune=
new THREE.Mesh(
new THREE.SphereGeometry(
rand(5,13),
12,
8
),
mat(
Math.random()>.5
?0xd8ad69
:0xc38e4b
)
);
dune.position.set(
rand(-115,115),
-2,
rand(-110,110)
);
dune.scale.y=.35;
scene.add(dune);
worldObjects.push(dune);
}
}
/* =========================================================
ENEMIES
========================================================= */
function createEnemy(){
const group=
new THREE.Group();
const body=
new THREE.Mesh(
new THREE.BoxGeometry(
1.3,1.7,.9
),
mat(0x263b59)
);
body.position.y=1.5;
group.add(body);
const head=
new THREE.Mesh(
new THREE.BoxGeometry(
1,1,1
),
mat(0xc98963)
);
head.position.y=2.75;
group.add(head);
const helmet=
new THREE.Mesh(
new THREE.BoxGeometry(
1.12,.32,1.08
),
mat(0x161b24)
);
helmet.position.y=3.2;
group.add(helmet);
const eyeMat=
new THREE.MeshStandardMaterial({
color:0xff0000,
emissive:0xff0000,
emissiveIntensity:3
});
const eye1=
new THREE.Mesh(
new THREE.BoxGeometry(
.16,.16,.08
),
eyeMat
);
const eye2=
eye1.clone();
eye1.position.set(
-.22,
2.82,
-.51
);
eye2.position.set(
.22,
2.82,
-.51
);
group.add(
eye1,
eye2
);
group.traverse(o=>{
if(o.isMesh){
o.castShadow=true;
o.receiveShadow=true;
}
});
return group;
}
function spawnEnemies(){
const d=
difficulty[currentDifficulty];
for(let i=0;i<d.count;i++){
const group=
createEnemy();
let x,z;
do{
x=rand(-115,115);
z=rand(-105,105);
}while(
Math.hypot(
x-player.x,
z-player.z
)<30
);
group.position.set(
x,
0,
z
);
scene.add(group);
enemies.push({
group,
hp:d.hp,
maxHp:d.hp,
dead:false,
vx:0,
vy:0,
vz:0,
nextAttack:
Date.now()+
Math.random()*1000
});
}
}
/* =========================================================
GUN
========================================================= */
function createGun(){
gunGroup=
new THREE.Group();
gunGroup.position.set(
.48,
-.38,
-.82
);
camera.add(
gunGroup
);
const body=
new THREE.Mesh(
new THREE.BoxGeometry(
.34,.3,1.1
),
mat(0x222222)
);
body.userData.weaponPart=true;
body.position.z=-.45;
gunGroup.add(body);
const barrel=
new THREE.Mesh(
new THREE.CylinderGeometry(
.065,.065,.65,12
),
mat(0x111111)
);
barrel.rotation.x=
Math.PI/2;
barrel.position.z=-1.1;
gunGroup.add(barrel);
const flash=
new THREE.PointLight(
0xffaa22,
0,
6
);
flash.position.set(
0,0,-1.5
);
gunGroup.add(flash);
gunGroup.userData.flash=
flash;
}
function updateGunModel(){
if(!gunGroup)
return;
const color=
guns[currentGun].color;
gunGroup.userData.flash.color=
new THREE.Color(color);
gunGroup.traverse(o=>{
if(
o.isMesh &&
o.userData.weaponPart
)
o.material.color.setHex(
color
);
});
}
/* =========================================================
SPEED
========================================================= */
function getPlayerSpeed(){
return (
BASE_PLAYER_SPEED+
(speedLevel-1)*
SPEED_UPGRADE
);
}
/* =========================================================
SHOOTING
========================================================= */
function reload(){
if(
reloading ||
!running
)
return;
reloading=true;
message(
"🔄 RELOADING..."
);
reloadTimer=
setTimeout(()=>{
if(!running){
reloading=false;
return;
}
ammo=
guns[currentGun].ammo;
reloading=false;
reloadTimer=null;
updateHUD();
message(
"🔫 RELOADED"
);
},900);
}
function shoot(){
if(
!running ||
paused ||
reloading
)
return;
const gun=
guns[currentGun];
if(
Date.now()-lastShot<
gun.rate
)
return;
if(ammo<=0){
reload();
return;
}
lastShot=
Date.now();
ammo--;
const direction=
new THREE.Vector3(
0,0,-1
)
.applyQuaternion(
camera.quaternion
)
.normalize();
const start=
new THREE.Vector3();
gunGroup.getWorldPosition(
start
);
const mesh=
new THREE.Mesh(
new THREE.SphereGeometry(
currentGun==="bazooka"
?.18
:.06,
8,
8
),
new THREE.MeshStandardMaterial({
color:gun.color,
emissive:gun.color,
emissiveIntensity:2
})
);
mesh.position.copy(start);
scene.add(mesh);
if(
currentGun==="bazooka"
){
rockets.push({
mesh,
velocity:
direction
.clone()
.multiplyScalar(
gun.bulletSpeed
),
life:180,
damage:
gun.damage*
damageLevel,
knockback:
gun.knockback*
(1+blastLevel*.3)
});
}else{
bullets.push({
mesh,
velocity:
direction
.clone()
.multiplyScalar(
gun.bulletSpeed
),
life:150,
damage:
gun.damage*
damageLevel,
knockback:
gun.knockback*
(1+blastLevel*.25)
});
}
if(
gunGroup.userData.flash
)
gunGroup.userData.flash.intensity=4;
updateHUD();
if(ammo<=0)
reload();
}
/* =========================================================
ENEMY HIT
========================================================= */
function hitEnemy(
enemy,
damage,
knockback,
direction
){
if(enemy.dead)
return;
enemy.hp-=damage;
enemy.vx+=
direction.x*
knockback;
enemy.vz+=
direction.z*
knockback;
if(enemy.hp<=0)
killEnemy(enemy);
}
function killEnemy(enemy){
if(enemy.dead)
return;
enemy.dead=true;
score+=100;
money+=5000;
saveGameData();
message(
"💀 ENEMY DOWN +$5,000"
);
scene.remove(
enemy.group
);
setTimeout(()=>{
if(!running)
return;
const d=
difficulty[currentDifficulty];
let x,z;
do{
x=rand(-115,115);
z=rand(-105,105);
}while(
Math.hypot(
x-player.x,
z-player.z
)<30
);
enemy.hp=d.hp;
enemy.dead=false;
enemy.vx=0;
enemy.vy=0;
enemy.vz=0;
enemy.nextAttack=
Date.now()+500;
enemy.group.position.set(
x,
0,
z
);
scene.add(
enemy.group
);
},1000);
}
/* =========================================================
BULLETS
========================================================= */
function updateBullets(){
for(
let i=bullets.length-1;
i>=0;
i--
){
const b=
bullets[i];
b.mesh.position.add(
b.velocity
);
let hit=false;
for(
const enemy of enemies
){
if(enemy.dead)
continue;
const target=
enemy.group.position
.clone();
target.y+=1.5;
if(
b.mesh.position.distanceTo(
target
)<1.25
){
hitEnemy(
enemy,
b.damage,
b.knockback,
b.velocity
.clone()
.normalize()
);
hit=true;
break;
}
}
b.life--;
if(
hit ||
b.life<=0 ||
Math.abs(
b.mesh.position.x
)>EDGE ||
Math.abs(
b.mesh.position.z
)>EDGE
){
scene.remove(
b.mesh
);
b.mesh.geometry.dispose();
b.mesh.material.dispose();
bullets.splice(i,1);
}
}
}
/* =========================================================
ROCKETS
========================================================= */
function updateRockets(){
for(
let i=rockets.length-1;
i>=0;
i--
){
const r=
rockets[i];
r.mesh.position.add(
r.velocity
);
let explode=false;
for(
const enemy of enemies
){
if(enemy.dead)
continue;
const target=
enemy.group.position
.clone();
target.y+=1.5;
if(
r.mesh.position.distanceTo(
target
)<1.5
){
explode=true;
break;
}
}
r.life--;
if(
explode ||
r.life<=0 ||
Math.abs(
r.mesh.position.x
)>EDGE ||
Math.abs(
r.mesh.position.z
)>EDGE
){
const pos=
r.mesh.position.clone();
for(
const enemy of enemies
){
if(enemy.dead)
continue;
const target=
enemy.group.position
.clone();
target.y+=1.5;
const distance=
pos.distanceTo(
target
);
if(distance<12){
const power=
Math.max(
.1,
1-distance/12
);
const direction=
target
.clone()
.sub(pos)
.normalize();
hitEnemy(
enemy,
r.damage*power,
r.knockback*power,
direction
);
}
}
scene.remove(
r.mesh
);
r.mesh.geometry.dispose();
r.mesh.material.dispose();
rockets.splice(i,1);
message(
"💥 EXPLOSION!"
);
}
}
}
/* =========================================================
ENEMY PHYSICS
========================================================= */
function updateEnemyPhysics(){
for(
const enemy of enemies
){
if(enemy.dead)
continue;
enemy.group.position.x+=
enemy.vx;
enemy.group.position.z+=
enemy.vz;
enemy.vy-=.035;
enemy.group.position.y+=
enemy.vy;
enemy.vx*=.91;
enemy.vz*=.91;
if(
enemy.group.position.y<0
){
enemy.group.position.y=0;
enemy.vy=0;
}
enemy.group.position.x=
THREE.MathUtils.clamp(
enemy.group.position.x,
-EDGE+1,
EDGE-1
);
enemy.group.position.z=
THREE.MathUtils.clamp(
enemy.group.position.z,
-EDGE+1,
EDGE-1
);
}
}
/* =========================================================
ENEMIES
========================================================= */
function updateEnemies(){
const d=
difficulty[currentDifficulty];
for(
const enemy of enemies
){
if(enemy.dead)
continue;
const dx=
player.x-
enemy.group.position.x;
const dz=
player.z-
enemy.group.position.z;
const distance=
Math.hypot(
dx,
dz
);
if(distance>1.7){
const directionX=
dx/distance;
const directionZ=
dz/distance;
enemy.group.position.x+=
directionX*
d.speed;
enemy.group.position.z+=
directionZ*
d.speed;
}
enemy.group.rotation.y=
Math.atan2(
dx,
dz
);
if(
distance<=2.5 &&
Date.now()>=
enemy.nextAttack
){
health=
Math.max(
0,
health-d.damage
);
enemy.nextAttack=
Date.now()+
d.attackDelay;
updateHUD();
message(
"💥 ENEMY HIT YOU! -"+
d.damage+
" HP"
);
if(distance>.001){
const push=.28;
player.x+=
dx/distance*
push;
player.z+=
dz/distance*
push;
player.x=
THREE.MathUtils.clamp(
player.x,
-EDGE+.5,
EDGE-.5
);
player.z=
THREE.MathUtils.clamp(
player.z,
-EDGE+.5,
EDGE-.5
);
}
if(health<=0){
gameOver();
return;
}
}
}
}
/* =========================================================
PLAYER MOVEMENT
========================================================= */
function movePlayer(
dx,
dz
){
player.x+=dx;
player.z+=dz;
player.x=
THREE.MathUtils.clamp(
player.x,
-EDGE+.5,
EDGE-.5
);
player.z=
THREE.MathUtils.clamp(
player.z,
-EDGE+.5,
EDGE-.5
);
}
function updateKeyboard(){
if(
!running ||
paused
)
return;
let forward=0;
let side=0;
if(keys.w)
forward++;
if(keys.s)
forward--;
if(keys.a)
side--;
if(keys.d)
side++;
if(!forward && !side)
return;
const length=
Math.hypot(
forward,
side
);
forward/=length;
side/=length;
const speed=
getPlayerSpeed();
movePlayer(
-Math.sin(
player.yaw
)*
forward*
speed
+
Math.cos(
player.yaw
)*
side*
speed,
-Math.cos(
player.yaw
)*
forward*
speed
-
Math.sin(
player.yaw
)*
side*
speed
);
}
function updateMovement(){
const forward=-joyY;
const side=joyX;
if(
Math.abs(forward)+
Math.abs(side)<.01
)
return;
const length=
Math.hypot(
forward,
side
);
const f=
forward/
Math.max(1,length);
const s=
side/
Math.max(1,length);
const speed=
getPlayerSpeed();
movePlayer(
-Math.sin(
player.yaw
)*
f*
speed
+
Math.cos(
player.yaw
)*
s*
speed,
-Math.cos(
player.yaw
)*
f*
speed
-
Math.sin(
player.yaw
)*
s*
speed
);
}
/* =========================================================
CAMERA
========================================================= */
function updateCamera(){
camera.position.set(
player.x,
player.y,
player.z
);
camera.rotation.order=
"YXZ";
camera.rotation.y=
player.yaw;
camera.rotation.x=
player.pitch;
if(gunGroup){
gunGroup.rotation.z=
Math.sin(
Date.now()*.004
)*.01;
}
if(
gunGroup.userData.flash
){
gunGroup.userData.flash.intensity=
Math.max(
0,
gunGroup.userData.flash.intensity-
.8
);
}
}
/* =========================================================
HUD
========================================================= */
function updateHUD(){
$("healthBar").style.width=
Math.max(
0,
health
)+"%";
$("ammoText").textContent=
ammo;
$("maxAmmo").textContent=
guns[currentGun].ammo;
$("moneyText").textContent=
money.toLocaleString();
$("shopMoney").textContent=
money.toLocaleString();
$("mapText").textContent=
currentMap.toUpperCase();
$("difficultyText").textContent=
currentDifficulty.toUpperCase();
$("playerNameHUD").textContent=
playerName;
$("weaponName").textContent=
guns[currentGun]
.name
.toUpperCase();
$("upgradeText").textContent=
"DAMAGE x"+
damageLevel+
" | BLAST x"+
blastLevel+
" | SPEED x"+
speedLevel;
}
/* =========================================================
JOYSTICK
========================================================= */
function joystickMove(e){
const rect=
$("joystick")
.getBoundingClientRect();
const centerX=
rect.left+
rect.width/2;
const centerY=
rect.top+
rect.height/2;
let dx=
e.clientX-
centerX;
let dy=
e.clientY-
centerY;
const max=44;
const length=
Math.hypot(
dx,
dy
);
if(length>max){
dx=
dx/length*
max;
dy=
dy/length*
max;
}
joyX=dx/max;
joyY=dy/max;
$("stick").style.left=
`calc(50% + ${dx}px)`;
$("stick").style.top=
`calc(50% + ${dy}px)`;
}
function resetJoystick(){
joystickPointer=null;
joyX=0;
joyY=0;
$("stick").style.left="50%";
$("stick").style.top="50%";
}
$("joystick").addEventListener(
"pointerdown",
e=>{
if(
!running ||
paused
)
return;
e.preventDefault();
e.stopPropagation();
joystickPointer=
e.pointerId;
try{
$("joystick")
.setPointerCapture(
e.pointerId
);
}catch(error){}
joystickMove(e);
},
{passive:false}
);
$("joystick").addEventListener(
"pointermove",
e=>{
if(
joystickPointer===
e.pointerId
){
e.preventDefault();
joystickMove(e);
}
},
{passive:false}
);
["pointerup","pointercancel"]
.forEach(type=>{
$("joystick").addEventListener(
type,
e=>{
if(
joystickPointer===
e.pointerId
)
resetJoystick();
e.preventDefault();
},
{passive:false}
);
});
/* =========================================================
TOUCH CAMERA
========================================================= */
$("cameraArea").addEventListener(
"pointerdown",
e=>{
if(
!running ||
paused
)
return;
e.preventDefault();
e.stopPropagation();
cameraPointer=
e.pointerId;
lastCameraX=
e.clientX;
lastCameraY=
e.clientY;
try{
$("cameraArea")
.setPointerCapture(
e.pointerId
);
}catch(error){}
},
{passive:false}
);
$("cameraArea").addEventListener(
"pointermove",
e=>{
if(
cameraPointer!==
e.pointerId ||
!running ||
paused
)
return;
e.preventDefault();
const dx=
e.clientX-
lastCameraX;
const dy=
e.clientY-
lastCameraY;
lastCameraX=
e.clientX;
lastCameraY=
e.clientY;
player.yaw-=
dx*.006;
player.pitch+=
dy*.006;
player.pitch=
THREE.MathUtils.clamp(
player.pitch,
-1.45,
1.45
);
},
{passive:false}
);
["pointerup","pointercancel"]
.forEach(type=>{
$("cameraArea").addEventListener(
type,
e=>{
if(
cameraPointer===
e.pointerId
)
cameraPointer=null;
e.preventDefault();
},
{passive:false}
);
});
/* =========================================================
FIRE
========================================================= */
$("fireButton").addEventListener(
"pointerdown",
e=>{
e.preventDefault();
e.stopPropagation();
shoot();
},
{passive:false}
);
/* =========================================================
KEYBOARD
========================================================= */
window.addEventListener(
"keydown",
e=>{
const key=
e.key.toLowerCase();
keys[key]=true;
if(
key==="e" ||
key===" "
){
e.preventDefault();
shoot();
}
if(
key==="r" &&
running &&
!paused
){
reload();
}
if(
key==="escape" &&
running
){
paused=!paused;
resetJoystick();
cameraPointer=null;
if(paused)
show("pauseScreen");
else
$("pauseScreen")
.classList
.remove("active");
}
}
);
window.addEventListener(
"keyup",
e=>{
keys[
e.key.toLowerCase()
]=false;
}
);
/* =========================================================
PAUSE
========================================================= */
$("pauseButton").onclick=e=>{
e.preventDefault();
e.stopPropagation();
if(!running)
return;
paused=!paused;
resetJoystick();
cameraPointer=null;
if(paused)
show("pauseScreen");
else
$("pauseScreen")
.classList
.remove("active");
};
$("resumeButton").onclick=e=>{
e.preventDefault();
paused=false;
$("pauseScreen")
.classList
.remove("active");
};
$("pauseMenuButton").onclick=e=>{
e.preventDefault();
running=false;
paused=false;
resetJoystick();
hideGameUI();
show("mainMenu");
};
/* =========================================================
SOUND
========================================================= */
$("soundButton").onclick=e=>{
e.preventDefault();
soundEnabled=
!soundEnabled;
$("soundButton").textContent=
soundEnabled
?"🔊 SOUND"
:"🔇 SOUND";
};
/* =========================================================
HIDE GAME UI
========================================================= */
function hideGameUI(){
[
"hud",
"crosshair",
"ammo",
"weaponName",
"upgradeText",
"joystick",
"cameraArea",
"fireButton",
"pauseButton",
"soundButton"
]
.forEach(id=>{
$(id).style.display=
"none";
});
}
/* =========================================================
START GAME
========================================================= */
function startGame(){
running=true;
paused=false;
reloading=false;
if(reloadTimer){
clearTimeout(
reloadTimer
);
reloadTimer=null;
}
resetJoystick();
cameraPointer=null;
health=100;
score=0;
if(
!ownedGuns[currentGun]
)
currentGun="pistol";
ammo=
guns[currentGun].ammo;
player.x=0;
player.y=1.7;
player.z=0;
player.yaw=0;
player.pitch=0;
createMap();
spawnEnemies();
updateGunModel();
updateHUD();
updateShop();
document
.querySelectorAll(".screen")
.forEach(
s=>
s.classList
.remove("active")
);
$("hud").style.display=
"block";
$("crosshair").style.display=
"block";
$("ammo").style.display=
"block";
$("weaponName").style.display=
"block";
$("upgradeText").style.display=
"block";
$("joystick").style.display=
"block";
$("cameraArea").style.display=
"block";
$("fireButton").style.display=
"block";
$("pauseButton").style.display=
"block";
$("soundButton").style.display=
"block";
}
/* =========================================================
GAME OVER
========================================================= */
function gameOver(){
if(!running)
return;
running=false;
paused=false;
if(reloadTimer){
clearTimeout(
reloadTimer
);
reloadTimer=null;
}
reloading=false;
resetJoystick();
cameraPointer=null;
hideGameUI();
$("scoreText").textContent=
score;
show("gameOver");
}
$("againBtn").onclick=e=>{
e.preventDefault();
startGame();
};
$("gameOverMenuBtn").onclick=e=>{
e.preventDefault();
running=false;
paused=false;
hideGameUI();
show("mainMenu");
};
/* =========================================================
GAME LOOP
========================================================= */
function animate(){
requestAnimationFrame(
animate
);
if(
running &&
!paused
){
updateKeyboard();
updateMovement();
updateEnemyPhysics();
updateEnemies();
updateBullets();
updateRockets();
updateCamera();
}
renderer.render(
scene,
camera
);
}
/* =========================================================
RESIZE
========================================================= */
window.addEventListener(
"resize",
()=>{
if(!camera || !renderer)
return;
camera.aspect=
innerWidth/
innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(
innerWidth,
innerHeight
);
}
);
/* =========================================================
TOUCH PROTECTION
========================================================= */
document.addEventListener(
"contextmenu",
e=>{
if(running)
e.preventDefault();
}
);
window.addEventListener(
"blur",
()=>{
resetJoystick();
cameraPointer=null;
}
);
document.addEventListener(
"visibilitychange",
()=>{
if(document.hidden){
resetJoystick();
cameraPointer=null;
}
}
);
/* =========================================================
LOAD
========================================================= */
loadGameData();
$("menuPlayerName").textContent=
playerName;
$("playerNameHUD").textContent=
playerName;
init3D();
updateHUD();
updateShop();
</script>
</body>
</html>Game Source: Blast World 3D
Creator: BoldPenguin14
Libraries: three
Complexity: complex (4204 lines, 58.7 KB)
The full source code is displayed above on this page.
Remix Instructions
To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: blast-world-3d-boldpenguin14" to link back to the original. Then publish at arcadelab.ai/publish.