Boat game, built by Clover 35B A3B Preview
Hostedvia DaBenchCustom endpoint
275tok/s
First token included
24.9Ktokens
1m 31s
Show the code the model wroteHide the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Naval Combat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { overflow: hidden; background: #000; cursor: crosshair; font-family: 'Courier New', monospace; }
canvas { display: block; }
#hud { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; }
#health-bar-wrap { position: absolute; top: 20px; left: 20px; width: 220px; height: 22px; background: rgba(0,0,0,0.6); border: 2px solid rgba(255,255,255,0.7); border-radius: 3px; }
#health-fill { height: 100%; background: linear-gradient(to right, #cc0000, #ff4444); transition: width 0.2s; border-radius: 2px; }
#health-label { position: absolute; top: 24px; left: 26px; color: #fff; font-size: 11px; letter-spacing: 2px; text-shadow: 1px 1px 2px #000; }
#score-display { position: absolute; top: 20px; right: 20px; color: #fff; font-size: 22px; text-shadow: 2px 2px 4px rgba(0,0,0,0.9); }
#wave-warning { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #ffcc00; font-size: 28px; letter-spacing: 4px; text-shadow: 0 0 10px rgba(255,200,0,0.8); opacity: 0; transition: opacity 0.3s; }
#crosshair { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 28px; height: 28px; border: 2px solid rgba(255,255,255,0.85); border-radius: 50%; }
#crosshair::before, #crosshair::after { content: ''; position: absolute; background: rgba(255,255,255,0.85); }
#crosshair::before { width: 2px; height: 10px; top: 9px; left: 13px; }
#crosshair::after { width: 10px; height: 2px; top: 13px; left: 9px; }
#crosshair-dot { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 3px; height: 3px; background: #ff4444; border-radius: 50%; }
#controls-hint { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); color: rgba(255,255,255,0.6); font-size: 13px; text-align: center; text-shadow: 1px 1px 2px #000; }
#game-over-screen { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); display: none; justify-content: center; align-items: center; flex-direction: column; pointer-events: all; }
#game-over-screen h1 { color: #ff4444; font-size: 56px; margin-bottom: 10px; text-shadow: 0 0 20px rgba(255,0,0,0.6); }
#game-over-screen .final-score { color: #fff; font-size: 24px; margin-bottom: 30px; }
#game-over-screen button { padding: 15px 40px; font-size: 20px; font-family: 'Courier New', monospace; background: #fff; border: none; cursor: pointer; letter-spacing: 2px; transition: background 0.2s; }
#game-over-screen button:hover { background: #ddd; }
#minimap { position: absolute; bottom: 20px; right: 20px; width: 150px; height: 150px; border: 2px solid rgba(255,255,255,0.5); border-radius: 50%; background: rgba(0,20,40,0.5); overflow: hidden; }
#minimap-canvas { width: 100%; height: 100%; }
</style>
</head>
<body>
<div id="hud">
<div id="health-bar-wrap"><div id="health-fill"></div><div id="health-label">HULL INTEGRITY</div></div>
<div id="score-display">SCORE: 0</div>
<div id="wave-warning">⚠ STORM WAVE INCOMING ⚠</div>
<div id="crosshair"><div id="crosshair-dot"></div></div>
<div id="controls-hint">WASD / ARROWS — Move | MOUSE — Aim | CLICK — Fire | SPACE — Boost</div>
<div id="minimap"><canvas id="minimap-canvas" width="150" height="150"></canvas></div>
</div>
<div id="game-over-screen">
<h1>BOAT SUNK</h1>
<div class="final-score" id="final-score">Score: 0</div>
<button onclick="location.reload()">RESTART</button>
</div>
<script type="importmap">
{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js" } }
</script>
<script type="module">
import * as THREE from 'three';
// ─── CONSTANTS ──────────────────────────────────────────────
const WATER_SIZE = 500;
const BOAT_MASS = 1.0;
const BOAT_BUOYANCY_K = 18.0;
const BOAT_DRAG = 3.5;
const BOAT_ROT_DRAG = 4.0;
const ENGINE_THRUST = 12.0;
const STEERING_SPEED = 2.5;
const BULLET_SPEED = 45;
const ENEMY_BASE_SPEED = 4.5;
const PLAYER_HEALTH = 100;
const ENEMY_HEALTH = 30;
const BULLET_DAMAGE = 30;
const ENEMY_BULLET_DAMAGE = 8;
const SPAWN_RADIUS = 80;
const MAX_STORM_WAVES = 3;
// ─── SCENE SETUP ────────────────────────────────────────────
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x1a3a5c);
scene.fog = new THREE.FogExp2(0x1a3a5c, 0.004);
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.5, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
document.body.appendChild(renderer.domElement);
// ─── LIGHTS ─────────────────────────────────────────────────
const ambientLight = new THREE.AmbientLight(0x446688, 1.5);
scene.add(ambientLight);
const sunLight = new THREE.DirectionalLight(0xfff4e0, 4);
sunLight.position.set(50, 80, 30);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(2048, 2048);
sunLight.shadow.camera.left = -80;
sunLight.shadow.camera.right = 80;
sunLight.shadow.camera.top = 80;
sunLight.shadow.camera.bottom = -80;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 200;
sunLight.shadow.bias = -0.001;
scene.add(sunLight);
const hemiLight = new THREE.HemisphereLight(0x88bbdd, 0x002244, 0.8);
scene.add(hemiLight);
// ─── SKY DOME ───────────────────────────────────────────────
const skyGeo = new THREE.SphereGeometry(400, 32, 32);
const skyMat = new THREE.ShaderMaterial({
side: THREE.BackSide,
uniforms: {
uTopColor: { value: new THREE.Color(0x0a1a3a) },
uBottomColor: { value: new THREE.Color(0x4a8ab5) },
uOffset: { value: 20 },
uExponent: { value: 0.5 }
},
vertexShader: `
varying vec3 vWorldPos;
void main() {
vWorldPos = (modelMatrix * vec4(position, 1.0)).xyz;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 uTopColor;
uniform vec3 uBottomColor;
uniform float uOffset;
uniform float uExponent;
varying vec3 vWorldPos;
void main() {
vec3 dir = normalize(vWorldPos + uOffset);
float h = dir.y;
vec3 col = mix(uBottomColor, uTopColor, pow(max(h, 0.0), uExponent));
gl_FragColor = vec4(col, 1.0);
}
`
});
scene.add(new THREE.Mesh(skyGeo, skyMat));
// ─── WATER SHADER ───────────────────────────────────────────
const waterVertexShader = `
attribute vec3 position;
uniform mat4 modelMatrix;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform float uTime;
uniform int uStormCount;
uniform vec3 uStormPos[3];
uniform float uStormAmp[3];
uniform vec2 uStormDir[3];
uniform float uStormSpeed[3];
uniform float uStormK[3];
varying vec3 vWorldPos;
varying vec3 vNormal;
varying vec3 vViewDir;
varying float vFoam;
vec3 gerstnerWave(vec3 p, float amp, float k, vec2 dir, float speed, float steepness) {
float phase = k * (dir.x * p.x + dir.y * p.z) + speed * uTime;
float cosP = cos(phase);
float sinP = sin(phase);
return vec3(
amp * steepness * cosP * dir.x,
amp * sinP,
amp * steepness * cosP * dir.y
);
}
vec3 totalDisplacement(vec3 p) {
vec3 d = vec3(0.0);
d += gerstnerWave(p, 0.9, 0.42, vec2(0.866, 0.5), 2.8, 0.25);
d += gerstnerWave(p, 0.55, 0.78, vec2(-0.5, 0.866), 3.5, 0.20);
d += gerstnerWave(p, 0.35, 1.26, vec2(-0.866, -0.5), 4.2, 0.15);
d += gerstnerWave(p, 0.22, 2.09, vec2(0.5, -0.866), 5.0, 0.10);
for (int i = 0; i < 3; i++) {
if (i >= uStormCount) break;
vec3 lp = p - uStormPos[i];
float dist = length(lp.xz);
float rad = 1.0 / uStormK[i];
float falloff = 0.5 * (1.0 + cos(3.14159 * dist / rad));
falloff = max(falloff, 0.0);
d += gerstnerWave(lp, uStormAmp[i], uStormK[i], uStormDir[i], uStormSpeed[i], 0.35) * falloff;
}
return d;
}
void main() {
vec3 pos = position;
vec3 disp = totalDisplacement(pos);
vec3 displaced = pos + disp;
vWorldPos = (modelMatrix * vec4(displaced, 1.0)).xyz;
float eps = 0.15;
vec3 p0 = pos + totalDisplacement(pos);
vec3 px = pos + vec3(eps, 0.0, 0.0) + totalDisplacement(pos + vec3(eps, 0.0, 0.0));
vec3 pz = pos + vec3(0.0, 0.0, eps) + totalDisplacement(pos + vec3(0.0, 0.0, eps));
vec3 t1 = normalize(px - p0);
vec3 t2 = normalize(pz - p0);
vNormal = normalize(cross(t1, t2));
vViewDir = normalize(cameraPosition - vWorldPos);
float steep = 0.0;
for (int i = 0; i < 4; i++) {
float a[4]; a[0]=0.9; a[1]=0.55; a[2]=0.35; a[3]=0.22;
float k[4]; k[0]=0.42; k[1]=0.78; k[2]=1.26; k[3]=2.09;
vec2 d[4]; d[0]=vec2(0.866,0.5); d[1]=vec2(-0.5,0.866); d[2]=vec2(-0.866,-0.5); d[3]=vec2(0.5,-0.866);
float phase = k[i] * (d[i].x * pos.x + d[i].y * pos.z) + (2.8+i*0.7)*uTime;
steep += abs(sin(phase)) * a[i] * k[i];
}
vFoam = smoothstep(0.3, 0.8, steep);
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(displaced, 1.0);
}
`;
const waterFragmentShader = `
varying vec3 vWorldPos;
varying vec3 vNormal;
varying vec3 vViewDir;
varying float vFoam;
uniform vec3 uSunDir;
uniform vec3 uSunColor;
uniform vec3 uDeepColor;
uniform vec3 uWaterColor;
uniform vec3 uFoamColor;
uniform float uTime;
void main() {
vec3 N = normalize(vNormal);
vec3 V = normalize(vViewDir);
float fresnel = pow(1.0 - max(dot(N, V), 0.0), 3.5);
float depthFactor = max(dot(N, V), 0.0);
vec3 color = mix(uDeepColor, uWaterColor, depthFactor * 0.7 + 0.3);
vec3 reflectDir = reflect(-V, N);
float skyMix = pow(max(reflectDir.y, 0.0), 2.0);
vec3 skyCol = mix(vec3(0.29, 0.54, 0.71), vec3(0.04, 0.10, 0.23), skyMix);
color = mix(color, skyCol, fresnel * 0.6);
vec3 H = normalize(uSunDir + V);
float spec1 = pow(max(dot(N, H), 0.0), 512.0);
float spec2 = pow(max(dot(N, H), 0.0), 64.0) * 0.3;
color += uSunColor * (spec1 * 3.0 + spec2 * 0.5);
float foam = vFoam * (0.5 + 0.5 * pow(max(dot(N, V), 0.0), 2.0));
color = mix(color, uFoamColor, foam * 0.6);
float dist = length(vWorldPos.xz);
float fogFactor = exp(-dist * 0.004);
vec3 fogCol = vec3(0.10, 0.23, 0.36);
color = mix(color, fogCol, 1.0 - fogFactor);
gl_FragColor = vec4(color, 1.0);
}
`;
const waterGeo = new THREE.PlaneGeometry(WATER_SIZE, WATER_SIZE, 256, 256);
waterGeo.rotateX(-Math.PI / 2);
const waterUniforms = {
uTime: { value: 0 },
uSunDir: { value: new THREE.Vector3(50, 80, 30).normalize() },
uSunColor: { value: new THREE.Color(0xfff4e0) },
uDeepColor: { value: new THREE.Color(0x001830) },
uWaterColor: { value: new THREE.Color(0x005580) },
uFoamColor: { value: new THREE.Color(0xddeeff) },
uStormCount: { value: 0 },
uStormPos: Array.from({length: 3}, () => new THREE.Vector3()),
uStormAmp: [0, 0, 0],
uStormDir: [new THREE.Vector2(1,0), new THREE.Vector2(0,1), new THREE.Vector2(-1,0)],
uStormSpeed: [0, 0, 0],
uStormK: [0, 0, 0]
};
const waterMat = new THREE.ShaderMaterial({
vertexShader: waterVertexShader,
fragmentShader: waterFragmentShader,
uniforms: waterUniforms
});
const waterMesh = new THREE.Mesh(waterGeo, waterMat);
waterMesh.receiveShadow = true;
scene.add(waterMesh);
function getWaterHeight(x, z, t) {
let y = 0;
const waves = [
{a:0.9, k:0.42, d:[0.866,0.5], sp:2.8},
{a:0.55, k:0.78, d:[-0.5,0.866], sp:3.5},
{a:0.35, k:1.26, d:[-0.866,-0.5], sp:4.2},
{a:0.22, k:2.09, d:[0.5,-0.866], sp:5.0}
];
for (const w of waves) {
const phase = w.k * (w.d[0]*x + w.d[1]*z) + w.sp * t;
y += w.a * Math.sin(phase);
}
for (const sw of activeStorms) {
const dx = x - sw.pos.x, dz = z - sw.pos.z;
const dist = Math.sqrt(dx*dx + dz*dz);
const rad = 1/sw.k;
const falloff = Math.max(0, 0.5*(1+Math.cos(Math.PI*dist/rad)));
const phase = sw.k * (sw.dir.x*dx + sw.dir.y*dz) + sw.speed * t;
y += sw.amplitude * Math.sin(phase) * falloff;
}
return y;
}
// ─── BOAT ───────────────────────────────────────────────────
function createBoat(color, isPlayer) {
const group = new THREE.Group();
const hullMat = new THREE.MeshStandardMaterial({ color, roughness: 0.3, metalness: 0.1 });
const darkMat = new THREE.MeshStandardMaterial({ color: 0x222222, roughness: 0.5 });
const glassMat = new THREE.MeshStandardMaterial({ color: 0x112233, roughness: 0.1, metalness: 0.8 });
// Hull
const hullShape = new THREE.Shape();
hullShape.moveTo(-1.2, -2.5);
hullShape.lineTo(1.2, -2.5);
hullShape.lineTo(1.2, 1.5);
hullShape.quadraticCurveTo(1.2, 2.8, 0, 3.2);
hullShape.quadraticCurveTo(-1.2, 2.8, -1.2, 1.5);
hullShape.lineTo(-1.2, -2.5);
const extrudeSettings = { depth: 2.4, bevelEnabled: true, bevelThickness: 0.1, bevelSize: 0.1, bevelSegments: 3 };
const hullGeo = new THREE.ExtrudeGeometry(hullShape, extrudeSettings);
const hull = new THREE.Mesh(hullGeo, hullMat);
hull.rotation.x = -Math.PI / 2;
hull.position.y = 0.3;
hull.castShadow = true;
hull.receiveShadow = true;
group.add(hull);
// Cabin
const cabinGeo = new THREE.BoxGeometry(1.6, 1.2, 1.8);
const cabin = new THREE.Mesh(cabinGeo, hullMat);
cabin.position.set(0, 1.2, -0.2);
cabin.castShadow = true;
group.add(cabin);
// Windshield
const wsGeo = new THREE.BoxGeometry(1.4, 0.8, 0.1);
const ws = new THREE.Mesh(wsGeo, glassMat);
ws.position.set(0, 1.5, 0.65);
ws.rotation.x = -0.2;
group.add(ws);
// Deck
const deckGeo = new THREE.BoxGeometry(2.2, 0.15, 3.5);
const deck = new THREE.Mesh(deckGeo, darkMat);
deck.position.y = 0.7;
group.add(deck);
// Railings
const railGeo = new THREE.CylinderGeometry(0.05, 0.05, 2.4);
for (let sx of [-1.1, 1.1]) {
const rail = new THREE.Mesh(railGeo, darkMat);
rail.position.set(sx, 1.0, 0);
rail.rotation.z = Math.PI / 2;
group.add(rail);
}
// Mast
const mastGeo = new THREE.CylinderGeometry(0.06, 0.08, 2.5);
const mast = new THREE.Mesh(mastGeo, darkMat);
mast.position.set(0, 2.2, -0.5);
group.add(mast);
group.userData.isPlayer = isPlayer;
return group;
}
const playerBoat = createBoat(0xeeeeee, true);
playerBoat.position.set(0, 0, 0);
scene.add(playerBoat);
// ─── GAME STATE ─────────────────────────────────────────────
const gameState = {
health: PLAYER_HEALTH,
score: 0,
gameOver: false,
enemies: [],
projectiles: [],
enemyProjectiles: [],
particles: [],
stormWaves: [],
activeStorms: [],
stormTimer: 0,
stormCooldown: 10,
spawnTimer: 0,
spawnCooldown: 5,
scoreMultiplier: 1,
boostActive: false
};
// ─── BOAT PHYSICS ───────────────────────────────────────────
const boatPhysics = {
position: new THREE.Vector3(0, 0, 0),
velocity: new THREE.Vector3(),
angularVelocity: new THREE.Vector3(),
rotation: new THREE.Euler(0, 0, 0, 'YXZ'),
yaw: 0,
pitch: 0,
roll: 0,
forward: new THREE.Vector3(0, 0, 1),
right: new THREE.Vector3(1, 0, 0),
up: new THREE.Vector3(0, 1, 0)
};
// ─── INPUT ──────────────────────────────────────────────────
const keys = {};
let mouseX = 0, mouseY = 0;
let mouseWorldX = 0, mouseWorldZ = 0;
let isMouseDown = false;
let lastShotTime = 0;
window.addEventListener('keydown', e => { keys[e.code] = true; e.preventDefault(); });
window.addEventListener('keyup', e => { keys[e.code] = false; });
window.addEventListener('mousemove', e => {
mouseX = (e.clientX / innerWidth) * 2 - 1;
mouseY = -(e.clientY / innerHeight) * 2 + 1;
});
window.addEventListener('mousedown', () => { isMouseDown = true; });
window.addEventListener('mouseup', () => { isMouseDown = false; });
function updateMouseWorld() {
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(new THREE.Vector2(mouseX, mouseY), camera);
const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -playerBoat.position.y);
const target = new THREE.Vector3();
raycaster.ray.intersectPlane(plane, target);
if (target) { mouseWorldX = target.x; mouseWorldZ = target.z; }
}
// ─── ENEMY SPAWNING ─────────────────────────────────────────
function spawnEnemy() {
const angle = Math.random() * Math.PI * 2;
const dist = SPAWN_RADIUS + Math.random() * 30;
const x = playerBoat.position.x + Math.cos(angle) * dist;
const z = playerBoat.position.z + Math.sin(angle) * dist;
const enemyGroup = createBoat(0xcc2222, false);
enemyGroup.position.set(x, 0, z);
enemyGroup.userData = {
health: ENEMY_HEALTH,
speed: ENEMY_BASE_SPEED + Math.random() * 1.5,
shootTimer: Math.random() * 3,
shootInterval: 2 + Math.random() * 2,
dodgeTimer: 0,
alive: true
};
scene.add(enemyGroup);
gameState.enemies.push(enemyGroup);
}
// ─── PROJECTILES ────────────────────────────────────────────
function fireProjectile(origin, direction, isPlayer) {
const geo = new THREE.SphereGeometry(isPlayer ? 0.12 : 0.15, 8, 8);
const mat = new THREE.MeshStandardMaterial({
color: isPlayer ? 0xffaa00 : 0xff2200,
emissive: isPlayer ? 0xff6600 : 0xff0000,
emissiveIntensity: 2
});
const mesh = new THREE.Mesh(geo, mat);
mesh.position.copy(origin);
mesh.castShadow = true;
scene.add(mesh);
const trailGeo = new THREE.CylinderGeometry(0.03, 0.08, 0.6);
const trailMat = new THREE.MeshBasicMaterial({ color: isPlayer ? 0xffaa00 : 0xff2200, transparent: true, opacity: 0.5 });
const trail = new THREE.Mesh(trailGeo, trailMat);
mesh.add(trail);
trail.rotation.x = Math.PI / 2;
trail.position.z = -0.3;
const proj = {
mesh,
velocity: direction.clone().multiplyScalar(BULLET_SPEED),
life: 3,
isPlayer,
damage: isPlayer ? BULLET_DAMAGE : ENEMY_BULLET_DAMAGE
};
if (isPlayer) gameState.projectiles.push(proj);
else gameState.enemyProjectiles.push(proj);
}
// ─── PARTICLES ──────────────────────────────────────────────
function spawnParticles(position, count, color, speed, life, size) {
const geo = new THREE.BufferGeometry();
const positions = new Float32Array(count * 3);
const velocities = [];
for (let i = 0; i < count; i++) {
positions[i*3] = position.x + (Math.random()-0.5)*0.5;
positions[i*3+1] = position.y + Math.random()*0.5;
positions[i*3+2] = position.z + (Math.random()-0.5)*0.5;
velocities.push(new THREE.Vector3(
(Math.random()-0.5)*speed,
Math.random()*speed*0.8 + speed*0.3,
(Math.random()-0.5)*speed
));
}
geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const mat = new THREE.PointsMaterial({
color, size: size || 0.3, transparent: true, opacity: 1,
blending: THREE.AdditiveBlending, depthWrite: false
});
const points = new THREE.Points(geo, mat);
scene.add(points);
gameState.particles.push({
mesh: points,
velocities,
life,
maxLife: life,
age: 0
});
}
function spawnExplosion(position) {
spawnParticles(position, 25, 0xff6600, 6, 1.2, 0.4);
spawnParticles(position, 15, 0xffaa00, 4, 0.8, 0.3);
spawnParticles(position, 8, 0xff2200, 8, 1.5, 0.5);
}
function spawnSplash(position) {
spawnParticles(position, 12, 0xaaddff, 3, 0.8, 0.2);
}
// ─── STORM WAVES ────────────────────────────────────────────
function spawnStormWave() {
const angle = Math.random() * Math.PI * 2;
const dist = 40 + Math.random() * 30;
const pos = new THREE.Vector3(
playerBoat.position.x + Math.cos(angle) * dist,
0,
playerBoat.position.z + Math.sin(angle) * dist
);
const dir = new THREE.Vector2().subVectors(
new THREE.Vector2(playerBoat.position.x, playerBoat.position.z),
new THREE.Vector2(pos.x, pos.z)
).normalize();
const amplitude = 2 + Math.random() * 2.5;
const wavelength = 20 + Math.random() * 20;
const k = 2 * Math.PI / wavelength;
const speed = Math.sqrt(9.81 * k);
const storm = { pos, dir, amplitude, k, speed, life: 8 + Math.random() * 4, age: 0 };
gameState.stormWaves.push(storm);
const warning = document.getElementById('wave-warning');
warning.style.opacity = '1';
setTimeout(() => { warning.style.opacity = '0'; }, 2000);
}
function updateStorms(dt) {
for (let i = gameState.stormWaves.length - 1; i >= 0; i--) {
const sw = gameState.stormWaves[i];
sw.age += dt;
sw.life -= dt;
if (sw.life <= 0) {
gameState.stormWaves.splice(i, 1);
continue;
}
const intensity = Math.sin(Math.PI * (sw.age / sw.life));
sw.pos.add(dir => {}); // keep position fixed, wave propagates through it
// Push boat if nearby
const dx = playerBoat.position.x - sw.pos.x;
const dz = playerBoat.position.z - sw.pos.z;
const dist = Math.sqrt(dx*dx + dz*dz);
const rad = 1/sw.k;
if (dist < rad * 2 && intensity > 0.1) {
const falloff = Math.max(0, 0.5*(1+Math.cos(Math.PI*dist/rad)));
const forceMag = sw.amplitude * intensity * falloff * 8;
const nx = dx/dist || 0, nz = dz/dist || 0;
boatPhysics.velocity.x += nx * forceMag * dt;
boatPhysics.velocity.z += nz * forceMag * dt;
boatPhysics.angularVelocity.y += (nx * dz - nz * dx) * forceMag * dt * 0.05;
if (dist < rad && Math.random() < 0.3) {
spawnSplash(playerBoat.position.clone().add(new THREE.Vector3((Math.random()-0.5)*2, 0, (Math.random()-0.5)*2)));
}
}
}
// Update uniforms
gameState.activeStorms = gameState.stormWaves.filter(sw => sw.life > 0);
waterUniforms.uStormCount.value = gameState.activeStorms.length;
for (let i = 0; i < 3; i++) {
if (i < gameState.activeStorms.length) {
const sw = gameState.activeStorms[i];
waterUniforms.uStormPos[i].copy(sw.pos);
waterUniforms.uStormAmp[i] = sw.amplitude;
waterUniforms.uStormDir[i].copy(sw.dir);
waterUniforms.uStormSpeed[i] = sw.speed;
waterUniforms.uStormK[i] = sw.k;
} else {
waterUniforms.uStormAmp[i] = 0;
}
}
}
// ─── UPDATE FUNCTIONS ───────────────────────────────────────
function updateBoatPhysics(dt) {
const bp = boatPhysics;
const wh = getWaterHeight(bp.position.x, bp.position.z, performance.now()/1000);
// Engine input
let throttle = 0;
if (keys['KeyW'] || keys['ArrowUp']) throttle = 1;
if (keys['KeyS'] || keys['ArrowDown']) throttle = -0.5;
gameState.boostActive = throttle > 0 && keys['Space'];
const thrustMult = gameState.boostActive ? 1.8 : 1.0;
// Steering
let steerInput = 0;
if (keys['KeyA'] || keys['ArrowLeft']) steerInput = 1;
if (keys['KeyD'] || keys['ArrowRight']) steerInput = -1;
// Forward/right vectors based on yaw
bp.forward.set(Math.sin(bp.yaw), 0, Math.cos(bp.yaw));
bp.right.set(Math.cos(bp.yaw), 0, -Math.sin(bp.yaw));
// Engine force
const engineForce = bp.forward.clone().multiplyScalar(throttle * ENGINE_THRUST * thrustMult);
bp.velocity.add(engineForce.multiplyScalar(dt));
// Steering (yaw rate proportional to speed)
const speed = bp.velocity.length();
const steerRate = steerInput * STEERING_SPEED * Math.min(speed / 5, 1) * dt;
bp.yaw += steerRate;
// Buoyancy
const buoyancyForce = (wh - bp.position.y) * BOAT_BUOYANCY_K;
bp.velocity.y += buoyancyForce * dt;
// Drag
bp.velocity.multiplyScalar(1 - BOAT_DRAG * dt);
// Gravity
bp.velocity.y -= 15 * dt;
// Update position
bp.position.add(bp.velocity.clone().multiplyScalar(dt));
// Keep above water minimum
if (bp.position.y < -2) bp.position.y = -2;
// Pitch and roll from wave slope
const whFront = getWaterHeight(bp.position.x + bp.forward.x * 2, bp.position.z + bp.forward.z * 2, performance.now()/1000);
const whBack = getWaterHeight(bp.position.x - bp.forward.x * 2, bp.position.z - bp.forward.z * 2, performance.now()/1000);
const whLeft = getWaterHeight(bp.position.x + bp.right.x * 1.5, bp.position.z + bp.right.z * 1.5, performance.now()/1000);
const whRight = getWaterHeight(bp.position.x - bp.right.x * 1.5, bp.position.z - bp.right.z * 1.5, performance.now()/1000);
const targetPitch = Math.atan2(whFront - whBack, 4);
const targetRoll = Math.atan2(whLeft - whRight, 3);
bp.pitch += (targetPitch - bp.pitch) * 5 * dt;
bp.roll += (targetRoll - bp.roll) * 5 * dt;
// Angular damping
bp.angularVelocity.multiplyScalar(1 - BOAT_ROT_DRAG * dt);
bp.yaw += bp.angularVelocity.y * dt;
// Auto-right when slow
if (speed < 1) {
bp.pitch *= (1 - 3 * dt);
bp.roll *= (1 - 3 * dt);
}
// Apply rotation to group
playerBoat.position.copy(bp.position);
playerBoat.rotation.set(bp.pitch, bp.yaw, bp.roll, 'YXZ');
// Tilt bow up/down based on movement
playerBoat.rotation.x += bp.pitch * 0.3;
}
function updateEnemies(dt) {
const bp = boatPhysics;
for (let i = gameState.enemies.length - 1; i >= 0; i--) {
const enemy = gameState.enemies[i];
if (!enemy.userData.alive) continue;
const dx = bp.position.x - enemy.position.x;
const dz = bp.position.z - enemy.position.z;
const dist = Math.sqrt(dx*dx + dz*dz);
// Face player
const targetAngle = Math.atan2(dx, dz);
let angleDiff = targetAngle - enemy.rotation.y;
while (angleDiff > Math.PI) angleDiff -= Math.PI * 2;
while (angleDiff < -Math.PI) angleDiff += Math.PI * 2;
enemy.rotation.y += angleDiff * 2 * dt;
// Movement
const forward = new THREE.Vector3(Math.sin(enemy.rotation.y), 0, Math.cos(enemy.rotation.y));
let moveSpeed = enemy.userData.speed;
// Dodge behavior
if (dist < 15 && enemy.userData.dodgeTimer <= 0) {
const dodgeDir = new THREE.Vector3(forward.z, 0, -forward.x).multiplyScalar(
Math.random() > 0.5 ? 1 : -1
);
enemy.position.add(dodgeDir.multiplyScalar(moveSpeed * 0.7 * dt));
enemy.userData.dodgeTimer = 1 + Math.random();
} else {
enemy.position.add(forward.clone().multiplyScalar(moveSpeed * dt));
enemy.userData.dodgeTimer -= dt;
}
// Shooting
enemy.userData.shootTimer -= dt;
if (enemy.userData.shootTimer <= 0 && dist < 50) {
enemy.userData.shootTimer = enemy.userData.shootInterval;
const shootDir = new THREE.Vector3(dx, 0, dz).normalize();
const origin = enemy.position.clone().add(forward.clone().multiplyScalar(2)).add(new THREE.Vector3(0, 1, 0));
fireProjectile(origin, shootDir, false);
}
// Collision with player
if (dist < 4) {
gameState.health -= 15 * dt;
spawnParticles(bp.position.clone().add(new THREE.Vector3(0, 0.5, 0)), 3, 0xff4400, 2, 0.5, 0.2);
}
}
}
function updateProjectiles(dt) {
// Player projectiles
for (let i = gameState.projectiles.length - 1; i >= 0; i--) {
const proj = gameState.projectiles[i];
proj.life -= dt;
proj.mesh.position.add(proj.velocity.clone().multiplyScalar(dt));
// Check enemy hits
let hit = false;
for (let j = gameState.enemies.length - 1; j >= 0; j--) {
const enemy = gameState.enemies[j];
if (!enemy.userData.alive) continue;
const dist = proj.mesh.position.distanceTo(enemy.position);
if (dist < 3) {
enemy.userData.health -= proj.damage;
spawnParticles(proj.mesh.position, 8, 0xffaa00, 4, 0.6, 0.25);
if (enemy.userData.health <= 0) {
enemy.userData.alive = false;
spawnExplosion(enemy.position.clone().add(new THREE.Vector3(0, 1, 0)));
scene.remove(enemy);
gameState.enemies.splice(j, 1);
gameState.score += 100 * gameState.scoreMultiplier;
}
hit = true;
break;
}
}
if (hit || proj.life <= 0) {
scene.remove(proj.mesh);
gameState.projectiles.splice(i, 1);
}
}
// Enemy projectiles
for (let i = gameState.enemyProjectiles.length - 1; i >= 0; i--) {
const proj = gameState.enemyProjectiles[i];
proj.life -= dt;
proj.mesh.position.add(proj.velocity.clone().multiplyScalar(dt));
// Check player hit
const dist = proj.mesh.position.distanceTo(playerBoat.position);
if (dist < 2.5) {
gameState.health -= proj.damage;
spawnParticles(proj.mesh.position, 6, 0xff4400, 3, 0.5, 0.2);
scene.remove(proj.mesh);
gameState.enemyProjectiles.splice(i, 1);
continue;
}
if (proj.life <= 0) {
scene.remove(proj.mesh);
gameState.enemyProjectiles.splice(i, 1);
}
}
}
function updateParticles(dt) {
for (let i = gameState.particles.length - 1; i >= 0; i--) {
const p = gameState.particles[i];
p.age += dt;
p.life -= dt;
if (p.life <= 0) {
scene.remove(p.mesh);
gameState.particles.splice(i, 1);
continue;
}
const positions = p.mesh.geometry.attributes.position.array;
for (let j = 0; j < p.velocities.length; j++) {
p.velocities[j].y -= 8 * dt;
positions[j*3] += p.velocities[j].x * dt;
positions[j*3+1] += p.velocities[j].y * dt;
positions[j*3+2] += p.velocities[j].z * dt;
}
p.mesh.geometry.attributes.position.needsUpdate = true;
p.mesh.material.opacity = Math.max(0, p.life / p.maxLife);
}
}
function updateCamera(dt) {
const bp = boatPhysics;
const targetOffset = new THREE.Vector3(0, 8, -14);
const targetPos = bp.position.clone().add(targetOffset);
// Aim direction influence
const aimDir = new THREE.Vector3(mouseWorldX - bp.position.x, 0, mouseWorldZ - bp.position.z).normalize();
const aimInfluence = new THREE.Vector3(aimDir.x * 3, 0, aimDir.z * 3);
targetPos.add(aimInfluence);
camera.position.lerp(targetPos, 3 * dt);
const lookTarget = bp.position.clone().add(new THREE.Vector3(aimDir.x * 5, 2, aimDir.z * 5));
camera.lookAt(lookTarget);
}
function updateSpawning(dt) {
gameState.spawnTimer -= dt;
if (gameState.spawnTimer <= 0 && gameState.enemies.filter(e => e.userData.alive).length < 8) {
spawnEnemy();
gameState.spawnTimer = gameState.spawnCooldown;
gameState.spawnCooldown = Math.max(1.5, 5 - gameState.score * 0.005);
}
gameState.stormTimer -= dt;
if (gameState.stormTimer <= 0) {
spawnStormWave();
gameState.stormTimer = gameState.stormCooldown + Math.random() * 5;
gameState.stormCooldown = Math.max(6, 15 - gameState.score * 0.01);
}
}
function updateHUD() {
const healthFill = document.getElementById('health-fill');
const healthPct = Math.max(0, gameState.health / PLAYER_HEALTH * 100);
healthFill.style.width = healthPct + '%';
if (healthPct < 30) {
healthFill.style.background = 'linear-gradient(to right, #ff0000, #ff4444)';
} else if (healthPct < 60) {
healthFill.style.background = 'linear-gradient(to right, #cc6600, #ff8800)';
} else {
healthFill.style.background = 'linear-gradient(to right, #cc0000, #ff4444)';
}
document.getElementById('score-display').textContent = 'SCORE: ' + gameState.score;
// Minimap
const mc = document.getElementById('minimap-canvas');
const ctx = mc.getContext('2d');
ctx.clearRect(0, 0, 150, 150);
ctx.fillStyle = 'rgba(0,20,40,0.3)';
ctx.fillRect(0, 0, 150, 150);
const scale = 0.8;
const cx = 75, cy = 75;
// Player
ctx.fillStyle = '#ffffff';
ctx.beginPath();
ctx.arc(cx, cy, 3, 0, Math.PI * 2);
ctx.fill();
// Enemies
ctx.fillStyle = '#ff4444';
for (const e of gameState.enemies) {
if (!e.userData.alive) continue;
const ex = cx + (e.position.x - playerBoat.position.x) * scale;
const ey = cy + (e.position.z - playerBoat.position.z) * scale;
if (ex > 0 && ex < 150 && ey > 0 && ey < 150) {
ctx.beginPath();
ctx.arc(ex, ey, 2, 0, Math.PI * 2);
ctx.fill();
}
}
// Storm warnings on minimap
for (const sw of gameState.activeStorms) {
const sx = cx + (sw.pos.x - playerBoat.position.x) * scale;
const sy = cy + (sw.pos.z - playerBoat.position.z) * scale;
if (sx > 0 && sx < 150 && sy > 0 && sy < 150) {
ctx.strokeStyle = 'rgba(255,200,0,0.5)';
ctx.beginPath();
ctx.arc(sx, sy, 5, 0, Math.PI * 2);
ctx.stroke();
}
}
}
function checkGameOver() {
if (gameState.gameOver) return;
if (gameState.health <= 0) {
gameState.gameOver = true;
document.getElementById('game-over-screen').style.display = 'flex';
document.getElementById('final-score').textContent = 'Score: ' + gameState.score;
spawnExplosion(playerBoat.position.clone().add(new THREE.Vector3(0, 1, 0)));
spawnParticles(playerBoat.position, 40, 0xff4400, 8, 2, 0.5);
spawnParticles(playerBoat.position, 30, 0xffaa00, 6, 1.5, 0.4);
}
}
// ─── SHOOTING ───────────────────────────────────────────────
function handleShooting(dt) {
if (!isMouseDown || gameState.gameOver) return;
const now = performance.now() / 1000;
if (now - lastShotTime < 0.15) return;
lastShotTime = now;
const bp = boatPhysics;
const aimDir = new THREE.Vector3(mouseWorldX - bp.position.x, 0, mouseWorldZ - bp.position.z).normalize();
const origin = bp.position.clone().add(bp.forward.clone().multiplyScalar(3)).add(new THREE.Vector3(0, 1.2, 0));
fireProjectile(origin, aimDir, true);
// Recoil
bp.velocity.sub(bp.forward.clone().multiplyScalar(0.5));
}
// ─── MAIN LOOP ──────────────────────────────────────────────
let lastTime = performance.now();
function animate(time) {
requestAnimationFrame(animate);
const dt = Math.min((time - lastTime) / 1000, 0.1);
lastTime = time;
if (!gameState.gameOver) {
updateMouseWorld();
updateBoatPhysics(dt);
updateEnemies(dt);
updateProjectiles(dt);
updateParticles(dt);
updateStorms(dt);
updateSpawning(dt);
handleShooting(dt);
updateHUD();
checkGameOver();
}
updateCamera(dt);
// Animate water
waterUniforms.uTime.value = time / 1000;
// Sun follows boat loosely
sunLight.position.set(
bp.position.x + 50,
80,
bp.position.z + 30
);
sunLight.target.position.copy(bp.position);
sunLight.target.updateMatrixWorld();
renderer.render(scene, camera);
}
// ─── RESIZE ─────────────────────────────────────────────────
window.addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
// ─── START ──────────────────────────────────────────────────
animate(0);
</script>
</body>
</html>Same prompt, other models
One email when a new model lands on the board or in the showcase. Unsubscribe anytime.