<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>PITCH / PLAY — 3D Football</title>
<style>
*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;overflow:hidden;background:#07110e;color:#f5f7f4;font-family:system-ui,-apple-system,"Segoe UI",sans-serif}
#game{position:fixed;inset:0}canvas{display:block;width:100%;height:100%;outline:none}
header{position:fixed;top:0;left:0;right:0;height:70px;z-index:2;display:flex;align-items:center;justify-content:space-between;padding:0 22px;background:linear-gradient(#06100ee8,#06100e00);pointer-events:none}
.logo{font-weight:950;letter-spacing:.16em;font-size:14px}.logo span{color:#c8ff38}.sub{font-size:10px;letter-spacing:.13em;color:#a7b9ac;margin-top:3px}
.scoreboard{display:flex;align-items:center;gap:10px;background:#08140fe8;border:1px solid #6d856d66;border-radius:8px;padding:8px 14px;box-shadow:0 8px 25px #0004}
.team{font-size:10px;color:#a8baad;letter-spacing:.1em}.score{font-size:24px;font-weight:900;font-variant-numeric:tabular-nums}.score .home{color:#c8ff38}.time{border-left:1px solid #48604c;padding-left:12px;font-size:15px;font-weight:800}
#help{position:fixed;bottom:16px;left:16px;z-index:2;padding:10px 13px;border-radius:8px;background:#07140edb;border:1px solid #91a98c44;font-size:11px;color:#d4e0d5;line-height:1.6;pointer-events:none}
#help b{color:#c8ff38}
#overlay{position:fixed;inset:0;z-index:5;display:flex;align-items:center;justify-content:center;background:linear-gradient(90deg,#03100cd9,#03100c55)}
.panel{width:min(490px,calc(100% - 32px));background:#091711f2;border:1px solid #70876a;border-radius:18px;padding:28px;box-shadow:0 30px 100px #0009}
.kicker{font-size:11px;font-weight:900;letter-spacing:.22em;color:#c8ff38}
h1{font-size:clamp(36px,7vw,60px);line-height:.92;margin:14px 0 16px;letter-spacing:-.045em}
p{color:#b8c9bc;font-size:14px;line-height:1.7}
.keys{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:20px 0}.key{background:#12241a;border:1px solid #294333;border-radius:9px;padding:10px;color:#b8c9bc;font-size:12px}.key strong{display:block;color:#fff;font-size:14px;margin-bottom:3px}
button{border:0;border-radius:10px;background:#c8ff38;color:#14200d;font-weight:950;letter-spacing:.08em;padding:15px 18px;width:100%;font-size:14px;cursor:pointer}
button:hover{filter:brightness(1.08)}
#message{position:fixed;top:20%;left:0;right:0;text-align:center;z-index:3;font-size:clamp(28px,5vw,56px);font-weight:1000;letter-spacing:.12em;text-shadow:0 4px 20px #000;opacity:0;pointer-events:none}
#mobile{display:none;position:fixed;bottom:18px;left:14px;right:14px;z-index:4;justify-content:space-between;align-items:end;pointer-events:none}
.pad{display:grid;grid-template-columns:repeat(3,46px);grid-template-rows:repeat(2,43px);gap:5px;pointer-events:auto}.pad button,.act button{background:#0b1b15d9;border:1px solid #d0e1d077;color:white;padding:0;width:auto;touch-action:none}.pad .blank{visibility:hidden}.act{display:flex;gap:7px;pointer-events:auto}.act button{min-width:56px;height:46px;font-size:10px}.act .shoot{background:#c8ff38;color:#14200d;border:0}
@media(max-width:700px){header{height:58px;padding:0 12px}.sub{display:none}.scoreboard{gap:7px;padding:6px 9px}.score{font-size:19px}.team{font-size:8px}.time{font-size:13px;padding-left:8px}#help{display:none}#mobile{display:flex}.panel{padding:22px}}
</style>
</head>
<body>
<div id="game"></div>
<header><div><div class="logo">PITCH<span>/</span>PLAY</div><div class="sub">3D FOOTBALL · ALL-STAR MATCH</div></div><div class="scoreboard"><div><div class="team">ALL-STARS</div><div class="score"><span class="home" id="homeScore">0</span> : <span id="awayScore">0</span></div></div><div class="time" id="clock">90:00</div></div></header>
<div id="help"><b>MOVE</b> WASD / ARROWS <b>SPRINT</b> SHIFT<br><b>SHOOT</b> SPACE長押し=強さ調整 <b>PASS + SWITCH</b> E <b>SKILLS</b> Q / F / R <b>SLIDE TACKLE</b> C <b>FOULS</b> cards / offside / set pieces</div>
<div id="message">GOAL!</div><div id="powerBar" style="position:fixed;bottom:70px;left:50%;transform:translateX(-50%);width:230px;height:14px;border:1px solid #c8ff38;border-radius:8px;background:#07140ee8;z-index:3;display:none;overflow:hidden;pointer-events:none"><div id="powerFill" style="height:100%;width:0;background:linear-gradient(90deg,#c8ff38,#ffd23a,#ff5a4a)"></div></div><div id="cardDisplay" style="position:fixed;top:82px;right:18px;z-index:3;font-weight:900;font-size:13px;text-align:right;pointer-events:none"></div><div id="setPieceHint" style="position:fixed;bottom:18px;left:50%;transform:translateX(-50%);z-index:3;background:#07140ee8;border:1px solid #c8ff38;border-radius:10px;padding:10px 16px;font-size:13px;font-weight:800;display:none;pointer-events:none">フリーキック:SPACEで再開</div>
<div id="mobile"><div class="pad"><button class="blank"></button><button data-key="w">▲</button><button class="blank"></button><button data-key="a">◀</button><button data-key="s">▼</button><button data-key="d">▶</button></div><div class="act"><button data-key="shift">SPRINT</button><button data-key="e">PASS / SWITCH</button><button data-key="q">SKILL</button><button data-key="c">SLIDE</button><button data-key="r">CHIP</button><button class="shoot" data-key=" ">SHOOT</button></div></div>
<div id="overlay"><div class="panel"><div class="kicker">MATCH DAY / 01</div><h1>OWN THE<br><span style="color:#c8ff38">PITCH.</span></h1><p>メッシ、エムバペ、ネイマール、ロナウドたちスター選手が登場!立体のピッチを走り、ゴールを狙おう。</p><div class="keys"><div class="key"><strong>W A S D / ↑ ↓ ← →</strong>移動・ドリブル</div><div class="key"><strong>SPACE 長押し</strong>溜めて離すとシュート(長いほど強い)</div><div class="key"><strong>SHIFT</strong>ダッシュ</div><div class="key"><strong>E</strong>味方へパスして操作を切り替え</div><div class="key"><strong>Q / F</strong>フェイント・ボールタッチ</div><div class="key"><strong>R</strong>ループシュート</div><div class="key"><strong>C</strong>スライディングタックル(守備)</div><div class="key"><strong>FREE KICK</strong>ファール後 SPACE でセットプレー</div></div><button id="start">KICK OFF →</button></div></div>
<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js';
const mount=document.querySelector('#game');
const scene=new THREE.Scene();scene.background=new THREE.Color(0x9bb4b8);scene.fog=new THREE.Fog(0x9bb4b8,42,105);
const camera=new THREE.PerspectiveCamera(52,innerWidth/innerHeight,.1,180);
const renderer=new THREE.WebGLRenderer({antialias:true,powerPreference:'high-performance'});
renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.setSize(innerWidth,innerHeight);renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;
renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.0;mount.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xdcecff,0x31502d,1.1));
const sun=new THREE.DirectionalLight(0xfff1d6,3.3);sun.position.set(-18,30,12);sun.castShadow=true;sun.shadow.mapSize.set(2048,2048);sun.shadow.camera.left=-36;sun.shadow.camera.right=36;sun.shadow.camera.top=40;sun.shadow.camera.bottom=-40;sun.shadow.bias=-.0003;scene.add(sun);
const fill=new THREE.DirectionalLight(0xc2e1ff,1.1);fill.position.set(18,15,-25);scene.add(fill);
const mat=(color,roughness=.8,metalness=0)=>new THREE.MeshStandardMaterial({color,roughness,metalness});
const fw=46,fl=72,MAXA=renderer.capabilities.getMaxAnisotropy(),rnd=(a,b)=>a+Math.random()*(b-a);
const cTex=(w,h,fn,rx=1,ry=1)=>{const c=document.createElement('canvas');c.width=w;c.height=h;fn(c.getContext('2d'),w,h);const t=new THREE.CanvasTexture(c);t.colorSpace=THREE.SRGBColorSpace;t.anisotropy=MAXA;if(rx!==1||ry!==1){t.wrapS=t.wrapT=THREE.RepeatWrapping;t.repeat.set(rx,ry)}return t};
// ---- real sky dome + sky-lit environment ----
const skyTex=cTex(1024,256,(c,w,h)=>{const g=c.createLinearGradient(0,0,0,h);g.addColorStop(0,'#2f6fc0');g.addColorStop(.3,'#6fa6de');g.addColorStop(.48,'#d6e5ee');g.addColorStop(.52,'#aab9b6');g.addColorStop(1,'#5b6b5e');c.fillStyle=g;c.fillRect(0,0,w,h);for(let i=0;i<46;i++){const x=Math.random()*w,y=rnd(25,95),r=rnd(30,90),gr=c.createRadialGradient(x,y,0,x,y,r);gr.addColorStop(0,'rgba(255,255,255,.34)');gr.addColorStop(1,'rgba(255,255,255,0)');c.fillStyle=gr;c.save();c.translate(x,y);c.scale(1,.28);c.translate(-x,-y);c.fillRect(x-r,y-r,r*2,r*2);c.restore()}});
const skyMat=new THREE.MeshBasicMaterial({map:skyTex,side:THREE.BackSide,fog:false}),skyGeo=new THREE.SphereGeometry(160,40,20);
const envScene=new THREE.Scene();envScene.add(new THREE.Mesh(skyGeo,skyMat));scene.environment=new THREE.PMREMGenerator(renderer).fromScene(envScene,0,.1,1000).texture;
scene.add(new THREE.Mesh(skyGeo,skyMat));scene.fog=new THREE.Fog(0xc9d9e2,60,135);
// ---- pitch: mown stripes, grass blades, worn goalmouths and painted lines in one texture ----
const PW=1380,PH=2160,sx=PW/fw,sz=PH/fl,X=x=>(x+fw/2)*sx,Z=z=>(z+fl/2)*sz;
const pitchTex=cTex(PW,PH,c=>{
for(let i=0;i<12;i++){c.fillStyle=i%2?'#2a7a3e':'#32894a';c.fillRect(0,i*PH/12,PW,PH/12+1)}
const cols=['#1f5f2f','#3a9552','#2a7438','#4aa760','#25683a'];c.globalAlpha=.28;
for(let i=0;i<90000;i++){c.strokeStyle=cols[i%5];const x=Math.random()*PW,y=Math.random()*PH;c.beginPath();c.moveTo(x,y);c.lineTo(x+rnd(-1.5,1.5),y+rnd(3,9));c.stroke()}
c.globalAlpha=1;[[0,-fl/2+4],[0,fl/2-4],[0,0]].forEach(([x,z])=>{const g=c.createRadialGradient(X(x),Z(z),0,X(x),Z(z),sx*7);g.addColorStop(0,'rgba(125,108,62,.4)');g.addColorStop(1,'rgba(125,108,62,0)');c.fillStyle=g;c.fillRect(0,0,PW,PH)});
c.strokeStyle=c.fillStyle='rgba(240,248,238,.94)';c.lineWidth=sx*.13;
const R=(a,b,d,e)=>c.strokeRect(X(a),Z(b),(d-a)*sx,(e-b)*sz),arc=(x,z,r,a0,a1)=>{c.beginPath();c.arc(X(x),Z(z),r*sx,a0,a1);c.stroke()};
R(-fw/2+.1,-fl/2+.1,fw/2-.1,fl/2-.1);c.beginPath();c.moveTo(X(-fw/2),Z(0));c.lineTo(X(fw/2),Z(0));c.stroke();arc(0,0,9.15,0,7);c.beginPath();c.arc(X(0),Z(0),.25*sx,0,7);c.fill();
for(const sg of [-1,1]){const g=sg*fl/2,b=sg<0?Math.PI/2:-Math.PI/2;R(-17.5,g-sg*.1,17.5,g-sg*16.5);R(-9,g-sg*.1,9,g-sg*5.5);c.beginPath();c.arc(X(0),Z(g-sg*11),.22*sx,0,7);c.fill();arc(0,g-sg*11,9.15,b-.93,b+.93)}
[[-1,-1,0],[1,-1,1],[1,1,2],[-1,1,3]].forEach(([a,b,k])=>arc(a*fw/2,b*fl/2,1,k*Math.PI/2,(k+1)*Math.PI/2))});
const pitch=new THREE.Mesh(new THREE.PlaneGeometry(fw,fl),new THREE.MeshStandardMaterial({map:pitchTex,bumpMap:pitchTex,bumpScale:.4,roughness:.96}));pitch.rotation.x=-Math.PI/2;pitch.position.y=-.02;pitch.receiveShadow=true;scene.add(pitch);
const apronTex=cTex(256,256,(c,w,h)=>{c.fillStyle='#2b6d3a';c.fillRect(0,0,w,h);c.globalAlpha=.3;for(let i=0;i<6000;i++){c.strokeStyle=['#1f5a2d','#3a8548','#2a6636'][i%3];const x=Math.random()*w,y=Math.random()*h;c.beginPath();c.moveTo(x,y);c.lineTo(x+rnd(-1,1),y+rnd(2,5));c.stroke()}},34,34);
const apron=new THREE.Mesh(new THREE.PlaneGeometry(150,150),new THREE.MeshStandardMaterial({map:apronTex,roughness:1}));apron.rotation.x=-Math.PI/2;apron.position.y=-.06;apron.receiveShadow=true;scene.add(apron);
// ---- goals with real net mesh and back frame ----
function makeGoal(z,dir){const g=new THREE.Group(),W=7.32,Hh=2.44,D=2.2,pm=new THREE.MeshStandardMaterial({color:0xffffff,roughness:.35,metalness:.1}),cy=(r,h,x,y,zz,rx,rz)=>{const m=new THREE.Mesh(new THREE.CylinderGeometry(r,r,h,12),pm);m.position.set(x,y,zz);m.rotation.set(rx||0,0,rz||0);m.castShadow=true;g.add(m)};
for(const x of [-W/2,W/2]){cy(.06,Hh,x,Hh/2,z);cy(.035,Hh,x,Hh/2,z+dir*D);cy(.03,D,x,Hh,z+dir*D/2,Math.PI/2)}cy(.06,W,0,Hh,z,0,Math.PI/2);cy(.035,W,0,Hh,z+dir*D,0,Math.PI/2);
const pts=[],L=(a,b)=>pts.push(...a,...b);for(let x=-W/2;x<=W/2+.01;x+=.2){L([x,0,z+dir*D],[x,Hh,z+dir*D]);L([x,Hh,z],[x,Hh,z+dir*D])}
for(let y=0;y<=Hh+.01;y+=.2){L([-W/2,y,z+dir*D],[W/2,y,z+dir*D]);for(const x of [-W/2,W/2])L([x,y,z],[x,y,z+dir*D])}
for(let d=0;d<=D+.01;d+=.2){L([-W/2,Hh,z+dir*d],[W/2,Hh,z+dir*d]);for(const x of [-W/2,W/2])L([x,0,z+dir*d],[x,Hh,z+dir*d])}
const geo=new THREE.BufferGeometry();geo.setAttribute('position',new THREE.Float32BufferAttribute(pts,3));g.add(new THREE.LineSegments(geo,new THREE.LineBasicMaterial({color:0xffffff,transparent:true,opacity:.5})));scene.add(g)}
makeGoal(-fl/2,-1);makeGoal(fl/2,1);
for(const a of [-1,1])for(const b of [-1,1]){const p=new THREE.Mesh(new THREE.CylinderGeometry(.02,.02,1.6,8),mat(0xf2f2f2));p.position.set(a*fw/2,.8,b*fl/2);scene.add(p);const f=new THREE.Mesh(new THREE.PlaneGeometry(.45,.3),new THREE.MeshStandardMaterial({color:0xffcc00,side:THREE.DoubleSide}));f.position.set(a*fw/2+.22,1.45,b*fl/2);scene.add(f)}
// ---- LED advertising boards ----
const adTex=cTex(1024,64,(c,w,h)=>{[['PITCH/PLAY','#c8ff38','#10281c'],['ALL-STARS','#ffffff','#0d3b66'],['MATCH DAY','#ffd23a','#7a1f1f'],['FOOTBALL','#ffffff','#1b1b1b']].forEach((t,i)=>{c.fillStyle=t[2];c.fillRect(i*256,0,256,h);c.fillStyle=t[1];c.font='bold 34px Arial';c.textAlign='center';c.textBaseline='middle';c.fillText(t[0],i*256+128,34)})});
function board(len,x,z){const t=adTex.clone();t.needsUpdate=true;t.wrapS=THREE.RepeatWrapping;t.repeat.set(len/8,1);const k=mat(0x111111),m=new THREE.Mesh(new THREE.BoxGeometry(len,.9,.15),[k,k,k,k,new THREE.MeshStandardMaterial({map:t,emissive:0xffffff,emissiveMap:t,emissiveIntensity:.55,roughness:.5}),k]);m.position.set(x,.45,z);m.rotation.y=Math.atan2(-x,-z);scene.add(m)}
for(const s of [-1,1]){board(fw+2,0,s*(fl/2+1.4));board(fl+2,s*(fw/2+1.4),0)}
// ---- tiered stands with a seated crowd (instanced) ----
const seatM=mat(0x2d4a63,.85),fans=[],fanCols=[0xd5ded6,0xe6b9a0,0x809cb3,0xf0e4c9,0xc7ff42,0xf4f4ed,0xb23a3a,0x30506e,0x222222,0xd9a07c,0x7a4c33];
function stand(side,ax){const len=ax==='z'?fw+30:fl;for(let k=0;k<14;k++){const dist=(ax==='z'?fl/2:fw/2)+5+k*.95,h=.55+k*.6,m=new THREE.Mesh(new THREE.BoxGeometry(ax==='z'?len:.95,h,ax==='z'?.95:len),seatM);m.position.set(ax==='z'?0:side*dist,h/2,ax==='z'?side*dist:0);scene.add(m);
for(let a=-len/2+.4;a<len/2-.3;a+=.58){if(Math.random()<.2)continue;fans.push({x:ax==='z'?a:side*dist,y:h,z:ax==='z'?side*dist:a,r:ax==='z'?(side>0?Math.PI:0):(side>0?-Math.PI/2:Math.PI/2),c:fanCols[Math.random()*fanCols.length|0],s:Math.random()})}}}
stand(1,'z');stand(-1,'z');stand(1,'x');stand(-1,'x');
{const N=fans.length,bI=new THREE.InstancedMesh(new THREE.BoxGeometry(.4,.5,.28),mat(0xffffff,.9),N),hI=new THREE.InstancedMesh(new THREE.SphereGeometry(.1,8,6),mat(0xffffff,.8),N),d=new THREE.Object3D(),c=new THREE.Color(),sk=[0xe6b99a,0xc98f6b,0x8a5a3c,0x5a3a28,0xf0cfb4];
fans.forEach((f,i)=>{const bob=f.s*.08;d.position.set(f.x,f.y+.3+bob,f.z);d.rotation.set(0,f.r,0);d.updateMatrix();bI.setMatrixAt(i,d.matrix);bI.setColorAt(i,c.setHex(f.c));d.position.y=f.y+.68+bob;d.updateMatrix();hI.setMatrixAt(i,d.matrix);hI.setColorAt(i,c.setHex(sk[f.s*5|0]))});scene.add(bI,hI)}
// ---- floodlight towers ----
for(const a of [-1,1])for(const b of [-1,1]){const xx=a*(fw/2+9),zz=b*(fl/2+3),tw=new THREE.Mesh(new THREE.BoxGeometry(.5,17,.5),mat(0x59636a,.5,.5));tw.position.set(xx,8.5,zz);scene.add(tw);
const hd=new THREE.Group();hd.position.set(xx,17,zz);const pm=new THREE.MeshBasicMaterial({color:0xfffbe8});for(let i=0;i<4;i++)for(let j=0;j<5;j++){const p=new THREE.Mesh(new THREE.BoxGeometry(.5,.35,.1),pm);p.position.set((j-2)*.6,(i-1.5)*.45,0);hd.add(p)}hd.lookAt(0,0,0);scene.add(hd);
const l=new THREE.PointLight(0xe4f2ff,24,40);l.position.set(xx,15.5,zz);scene.add(l)}
// ---- stadium shell: rear walls, canopy roofs with ribs, giant LED screens, dugouts, lamp glow, living crowd ----
let crowdBoost=0,lastKey='';const crowdU={uT:{value:0},uA:{value:.035}},screens=[];
scene.children.filter(o=>o.isInstancedMesh).forEach(m=>{m.material.onBeforeCompile=sh=>{sh.uniforms.uT=crowdU.uT;sh.uniforms.uA=crowdU.uA;sh.vertexShader='uniform float uT;uniform float uA;\n'+sh.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\n transformed.y+=pow(max(0.,sin(uT*3.1+instanceMatrix[3].x*1.3+instanceMatrix[3].z*2.1)),3.)*uA;')}});
const conc=mat(0x8d9396,.95),steel=mat(0xb9c2c8,.45,.55),dkM=mat(0x1b2226,.6);
function shell(s,ax){const len=ax==='z'?fw+30:fl,g=new THREE.Group(),b=ax==='z'?fl/2:fw/2;
if(ax==='z'){g.position.z=s*b;g.rotation.y=s>0?0:Math.PI}else{g.position.x=s*b;g.rotation.y=s>0?Math.PI/2:-Math.PI/2}
const add=(geo,m,x,y,z,rx)=>{const o=new THREE.Mesh(geo,m);o.position.set(x,y,z);if(rx)o.rotation.x=rx;g.add(o);return o};
add(new THREE.BoxGeometry(len,15,.5),conc,0,7.5,19.1);add(new THREE.BoxGeometry(len+2,.3,11),steel,0,14.4,13.9,-.07);add(new THREE.BoxGeometry(len+2,.9,.3),mat(0x2b3338,.5,.3),0,14.2,8.5);
for(let x=-len/2;x<=len/2;x+=6){add(new THREE.BoxGeometry(.25,.5,11),steel,x,14.1,13.9,-.07);add(new THREE.BoxGeometry(.3,14,.3),conc,x,7,19.1)}
scene.add(g)}
shell(1,'z');shell(-1,'z');shell(1,'x');shell(-1,'x');
function mkScreen(z,rot){const cv=document.createElement('canvas');cv.width=512;cv.height=192;const tx=new THREE.CanvasTexture(cv);tx.colorSpace=THREE.SRGBColorSpace;
const m=new THREE.Mesh(new THREE.PlaneGeometry(12,4.5),new THREE.MeshBasicMaterial({map:tx}));m.position.set(0,11.7,z);m.rotation.y=rot;scene.add(m);
const f=new THREE.Mesh(new THREE.BoxGeometry(12.6,5.1,.3),mat(0x14181a,.5,.4));f.position.set(0,11.7,z+Math.sign(z)*.2);scene.add(f);screens.push({cv,tx})}
mkScreen(-54.4,0);mkScreen(54.4,Math.PI);
function drawScreens(){const key=homeScore+':'+awayScore+':'+Math.floor(clock);if(key===lastKey)return;lastKey=key;
screens.forEach(({cv,tx})=>{const c=cv.getContext('2d');c.fillStyle='#07140e';c.fillRect(0,0,512,192);c.textAlign='center';c.fillStyle='#c8ff38';c.font='bold 30px Arial';c.fillText('PITCH / PLAY',256,38);
c.fillStyle='#fff';c.font='bold 88px Arial';c.fillText(homeScore+' : '+awayScore,256,130);c.fillStyle='#ffd23a';c.font='bold 34px Arial';c.fillText(Math.floor(clock)+"'",256,175);tx.needsUpdate=true})}
function venueTick(dt,t){crowdBoost*=Math.exp(-1.2*dt);crowdU.uT.value=t;crowdU.uA.value=.035+crowdBoost;drawScreens()}
function dugout(sx,col){const g=new THREE.Group();g.position.set(sx*(fw/2+3.55),0,0);scene.add(g);
const gl=new THREE.MeshPhysicalMaterial({color:0xcfe8ff,transparent:true,opacity:.28,roughness:.1}),add=(geo,m,x,y,z)=>{const o=new THREE.Mesh(geo,m);o.position.set(x,y,z);g.add(o);return o};
add(new THREE.BoxGeometry(1.8,.08,8.6),gl,0,2.1,0);add(new THREE.BoxGeometry(.08,1.7,8.6),gl,sx*.85,1.2,0);add(new THREE.BoxGeometry(1.8,1.2,.08),gl,0,1.1,4.3);add(new THREE.BoxGeometry(1.8,1.2,.08),gl,0,1.1,-4.3);
add(new THREE.BoxGeometry(.7,.1,8),dkM,sx*.4,.45,0);add(new THREE.BoxGeometry(.1,.5,8),dkM,sx*.7,.7,0);
const km=mat(col,.7),skm=[mat(0xe0b090,.8),mat(0x8a5a3c,.8),mat(0xc98f6b,.8)];
for(let i=0;i<7;i++){const z=-3.2+i*1.05;add(new THREE.CapsuleGeometry(.17,.33,4,8),km,sx*.35,.95,z);add(new THREE.SphereGeometry(.11,10,8),skm[i%3],sx*.35,1.42,z);add(new THREE.BoxGeometry(.5,.15,.22),dkM,sx*.1,.6,z)}}
dugout(1,0xc7ff42);dugout(-1,0xf4f4ed);
{const gt=cTex(64,64,c=>{const g=c.createRadialGradient(32,32,0,32,32,32);g.addColorStop(0,'rgba(255,250,230,1)');g.addColorStop(.25,'rgba(255,245,215,.45)');g.addColorStop(1,'rgba(255,245,215,0)');c.fillStyle=g;c.fillRect(0,0,64,64)}),gm=new THREE.SpriteMaterial({map:gt,blending:THREE.AdditiveBlending,depthWrite:false,transparent:true,fog:false});
for(const a of [-1,1])for(const b of [-1,1]){const sp=new THREE.Sprite(gm);sp.scale.set(9,9,1);sp.position.set(a*(fw/2+9),17,b*(fl/2+3));scene.add(sp)}}
const TX={};
function canvasTex(w,h,draw,rep){const c=document.createElement('canvas');c.width=w;c.height=h;draw(c.getContext('2d'),w,h);const t=new THREE.CanvasTexture(c);t.colorSpace=THREE.SRGBColorSpace;if(rep){t.wrapS=t.wrapT=THREE.RepeatWrapping;t.repeat.set(rep,rep)}t.anisotropy=4;return t}
const LOOK={star:{n:'MESSI',s:0x5e3b2a,h:0x120d0b,hs:'braids',b:0,e:0x20140e,sm:1},messi:{n:'MESSI',s:0xe3b08a,h:0x4a3322,hs:'side',b:2,e:0x5a3a22},mbappe:{n:'MBAPPÉ',s:0x6a4332,h:0x15110f,hs:'crop',b:0,e:0x2a1a12},neymar:{n:'NEYMAR',s:0xb98260,h:0xd9b46a,hs:'crop',b:1,e:0x3a2616},ronaldo:{n:'RONALDO',s:0xdca483,h:0x1b1410,hs:'slick',b:1,e:0x3a2616},haaland:{n:'HAALAND',s:0xf2c9ad,h:0xe0c36e,hs:'long',b:0,e:0x4a7aa8},salah:{n:'SALAH',s:0xa97352,h:0x14100e,hs:'curly',b:2,e:0x2a1a12},vini:{n:'VINÍCIUS',s:0x5b392a,h:0x120e0d,hs:'curly',b:0,e:0x20140e},courtois:{n:'COURTOIS',s:0xe8bd9b,h:0x2a2018,hs:'side',b:1,e:0x4a6a8a},ref:{n:'',s:0xd9a584,h:0x2a2018,hs:'crop',b:0,e:0x3a2a1a}};
function jawDeform(g){const p=g.attributes.position;for(let i=0;i<p.count;i++){const y=p.getY(i);if(y<0){const k=Math.pow(-y,1.3);p.setX(i,p.getX(i)*(1-.3*k));if(p.getZ(i)>0)p.setZ(i,p.getZ(i)*(1-.1*k))}}g.computeVertexNormals();return g}
const HGT={star:.97,messi:.91,mbappe:.98,neymar:.96,ronaldo:1.03,haaland:1.08,salah:.97,vini:.95,courtois:1.08};
function makePlayer(home=true,number=10,who='messi'){
const root=new THREE.Group(),body=new THREE.Group(),upper=new THREE.Group();root.add(body);body.add(upper);const L=LOOK[who]||LOOK.messi;
TX.knit=TX.knit||canvasTex(64,64,(c,w,h)=>{c.fillStyle='#f0f0f0';c.fillRect(0,0,w,h);for(let i=-h;i<w;i+=4){c.strokeStyle='rgba(0,0,0,.13)';c.lineWidth=1.2;c.beginPath();c.moveTo(i,0);c.lineTo(i+h,h);c.stroke();c.strokeStyle='rgba(255,255,255,.35)';c.beginPath();c.moveTo(i+2,h);c.lineTo(i+2+h,0);c.stroke()}},5);
TX.pore=TX.pore||canvasTex(128,128,(c,w,h)=>{c.fillStyle='#bbb';c.fillRect(0,0,w,h);for(let i=0;i<2600;i++){const v=120+Math.random()*120|0;c.fillStyle=`rgb(${v},${v},${v})`;c.fillRect(Math.random()*w,Math.random()*h,1+Math.random()*1.6,1+Math.random()*1.6)}},3);
const kit=who==='ref'?{j:0x17191d,s:0x17191d,k:0x17191d,t:'#e8e8e8'}:number===1?{j:0xff9f1c,s:0x15191c,k:0xff9f1c,t:'#1a1a1a'}:home?{j:0x1f4fb8,s:0x1f4fb8,k:0x1f4fb8,t:'#ffffff'}:{j:0xf4f4ed,s:0x202d36,k:0x26323b,t:'#252525'};
const fab=c=>new THREE.MeshStandardMaterial({color:c,roughness:.8,map:TX.knit,bumpMap:TX.knit,bumpScale:.5});
const skin=new THREE.MeshPhysicalMaterial({color:L.s,roughness:.58,bumpMap:TX.pore,bumpScale:.5,sheen:.6,sheenColor:new THREE.Color(0xffc9a8),sheenRoughness:.6,clearcoat:.05,clearcoatRoughness:.5});
const skinDark=mat(new THREE.Color(L.s).multiplyScalar(.62).getHex(),.7),lipM=mat(new THREE.Color(L.s).lerp(new THREE.Color(0x8a3f3a),.5).getHex(),.4);
const H2=home&&number!==1&&who!=='ref',baseM=mat(0x1b3f9a,.8),whiteM=mat(0xf0f0ea,.8);
const marble=(c,w,h)=>{for(let i=0;i<500;i++){const x=Math.random()*w,y=Math.random()*h;c.strokeStyle=Math.random()<.6?'rgba(110,170,235,.35)':'rgba(255,130,120,.2)';c.lineWidth=rnd(1,3);c.beginPath();c.moveTo(x,y);c.quadraticCurveTo(x+rnd(-14,14),y+rnd(-14,14),x+rnd(-18,18),y+rnd(-18,18));c.stroke()}};
TX.stripe=TX.stripe||canvasTex(256,256,(c,w,h)=>{const n=14,sw=w/n;for(let i=0;i<n;i++){c.fillStyle=i%2?'#c9242c':'#1f4fb8';c.fillRect(i*sw,0,sw+1,h)}marble(c,w,h)});
TX.marble=TX.marble||canvasTex(256,256,(c,w,h)=>{c.fillStyle='#1f4fb8';c.fillRect(0,0,w,h);marble(c,w,h)});
const jersey=H2?new THREE.MeshStandardMaterial({map:TX.stripe,bumpMap:TX.knit,bumpScale:.4,roughness:.78}):fab(kit.j),shorts=H2?new THREE.MeshStandardMaterial({map:TX.marble,bumpMap:TX.knit,bumpScale:.4,roughness:.78}):fab(kit.s),sock=fab(kit.k),trim=H2?mat(0xf4f4f4,.6):mat(new THREE.Color(kit.j).multiplyScalar(.7).getHex(),.7),hairM=mat(L.h,.42,.05),boot=H2?mat(0xf2f1ea,.4,.1):mat(0x14181a,.35,.1),bootAcc=mat(home?0xc9242c:0xf0f0f0,.4),sole=H2?mat(0xb9b9b0,.6):mat(0x07090a,.6);
const cyl=(a,b,h,m,s=16)=>new THREE.Mesh(new THREE.CylinderGeometry(a,b,h,s),m),sph=(r,m,x=1,y=1,z=1,s=14)=>{const o=new THREE.Mesh(new THREE.SphereGeometry(r,s,Math.max(8,s-4)),m);o.scale.set(x,y,z);return o};
const put=(g,o,x,y,z,sh=true)=>{o.position.set(x,y,z);o.castShadow=sh;g.add(o);return o};
// torso: lathe profile gives a V-taper from hips to shoulders
const prof=[[0,0],[.17,0],[.185,.15],[.225,.3],[.27,.45],[.292,.55],[.288,.62],[.25,.68],[.17,.72],[.09,.745],[0,.76]].map(p=>new THREE.Vector2(p[0],p[1]));
const torso=new THREE.Mesh(new THREE.LatheGeometry(prof,32),jersey);torso.scale.set(1,1,.68);put(upper,torso,0,.9,0);
const print=(a0,draw)=>{const t=canvasTex(256,256,draw);const m=new THREE.Mesh(new THREE.CylinderGeometry(.279,.279,.28,24,1,true,a0,.95),new THREE.MeshStandardMaterial({map:t,transparent:true,roughness:.8,depthWrite:false,polygonOffset:true,polygonOffsetFactor:-2}));m.scale.set(1,1,.68);put(upper,m,0,1.32,0,false)};
print(Math.PI-.475,(c,w)=>{c.fillStyle=kit.t;c.textAlign='center';c.font='bold 46px Arial';c.fillText(L.n,w/2,62);c.font='bold 150px Arial';c.fillText(String(number),w/2,205)});
print(-.475,(c,w)=>{c.fillStyle=kit.t;c.beginPath();c.arc(70,70,24,0,7);c.fill();c.textAlign='center';c.font='bold 26px Arial';c.fillText('PITCH/PLAY',w/2+10,150);c.fillRect(w/2-60,162,140,4)});
const collar=new THREE.Mesh(new THREE.TorusGeometry(.088,.017,8,24),trim);collar.rotation.x=Math.PI/2;collar.scale.set(1,1,1.15);put(upper,collar,0,1.645,.012,false);
put(upper,cyl(.055,.064,.13,skin,14),0,1.69,0);
// head with tapered jaw
const H=new THREE.Group();H.position.set(0,1.8,.012);upper.add(H);
const head=new THREE.Mesh(jawDeform(new THREE.SphereGeometry(1,32,24)),skin);head.scale.set(.098,.138,.115);head.castShadow=true;H.add(head);
for(const sd of [-1,1]){
put(H,sph(.012,skin,.8,2.4,1.5),sd*.099,-.005,-.004,false);
put(H,sph(.033,skinDark,1,.62,.3),sd*.044,.022,.092,false);
put(H,sph(.0215,mat(0xf4f1ea,.25),1,.78,.55),sd*.044,.02,.094,false);
put(H,sph(.0125,mat(L.e,.3),1,1,.4),sd*.044,.02,.108,false);
put(H,sph(.0062,mat(0x050505,.2),1,1,.4),sd*.044,.02,.1125,false);
const gl=put(H,sph(.0135,new THREE.MeshPhysicalMaterial({color:0xffffff,roughness:0,transparent:true,opacity:.28}),1,1,.5),sd*.044,.02,.111,false);
const lid=put(H,sph(.024,skin,1,.45,.6),sd*.044,.034,.097,false);lid.rotation.x=-.15;
const br=put(H,new THREE.Mesh(new THREE.BoxGeometry(.04,.0075,.011),hairM),sd*.046,.056,.097,false);br.rotation.z=sd*-.12;
put(H,sph(.0125,skin,1,.9,.9),sd*.0155,-.035,.108,false);
}
put(H,sph(.014,skin,.8,1.7,1),0,0,.108,false);put(H,sph(.0165,skin,.9,1.1,1.1),0,-.034,.114,false);
put(H,sph(.026,lipM,L.sm?1.35:1,.28,.45),0,-.067,.099+(L.b>1?.012:0),false);put(H,sph(.024,lipM,L.sm?1.35:1,.32,.5),0,-.076,.097+(L.b>1?.012:0),false);if(L.sm){put(H,sph(.027,mat(0xf6f3ea,.3),1,.32,.4),0,-.071,.1,false);for(const sd of [-1,1])put(H,sph(.03,skin,1,1,.8),sd*.052,-.04,.088,false)}
if(L.b){const bm=new THREE.MeshStandardMaterial({color:L.b>1?L.h:0x2b2018,roughness:1,transparent:L.b<2,opacity:L.b<2?.4:1});const bd=new THREE.Mesh(jawDeform(new THREE.SphereGeometry(1,28,12,0,Math.PI*2,.6*Math.PI,.35*Math.PI)),bm);bd.scale.set(.1,.141,.119);H.add(bd)}
// hair styles
const cap=(th,sc,rx)=>{const m=new THREE.Mesh(new THREE.SphereGeometry(1,28,16,0,Math.PI*2,0,th),hairM);m.scale.set(.102*sc,.142*sc,.12*sc);m.rotation.x=rx;m.castShadow=true;H.add(m)};
const hs=number===1&&who!=='courtois'?'crop':L.hs;
if(hs==='crop')cap(.5*Math.PI,1.03,-.18);
if(hs==='side'){cap(.56*Math.PI,1.05,-.3);put(H,sph(.07,hairM,1,.4,1),.015,.125,.05,false)}
if(hs==='slick'){cap(.56*Math.PI,1.05,-.4);put(H,sph(.075,hairM,1,.55,1.3),0,.128,.03,false)}
if(hs==='long'){cap(.58*Math.PI,1.05,-.4);put(H,sph(.052,hairM),0,.095,-.125,false);put(H,new THREE.Mesh(new THREE.CapsuleGeometry(.05,.13,4,10),hairM),0,-.02,-.1,false)}
if(hs==='braids'){cap(.55*Math.PI,1.04,-.3);
for(let i=0;i<10;i++){const a=(i-4.5)*.017,b=new THREE.Mesh(new THREE.CapsuleGeometry(.014,.3,3,6),hairM);b.position.set(a*3,-.1,-.12-Math.abs(i-4.5)*.003);b.rotation.set(-.12,0,a*1.5);b.castShadow=true;H.add(b)}
for(const sd of [-1,1])for(let i=0;i<3;i++){const b=new THREE.Mesh(new THREE.CapsuleGeometry(.013,.22,3,6),hairM);b.position.set(sd*(.1+i*.006),-.06,-.01-i*.03);b.rotation.set(0,0,sd*.05);H.add(b)}}
if(hs==='curly'){cap(.52*Math.PI,1.02,-.25);for(let i=0;i<46;i++){const a=Math.random()*Math.PI*2,ph=Math.random()*.52*Math.PI,x=Math.sin(ph)*Math.cos(a),y=Math.cos(ph),z=Math.sin(ph)*Math.sin(a);if(z>.45&&y<.7)continue;put(H,sph(.027,hairM,1,1,1,8),x*.108,y*.148,z*.126,false)}}
// hips & shorts
const pel=cyl(.205,.22,.25,shorts,24);pel.scale.z=.74;put(body,pel,0,.99,0);put(body,cyl(.208,.208,.03,trim,24),0,1.1,0,false).scale.z=.74;
const limbs=[];
for(const sd of [-1,1]){
// arm: shoulder > upper arm > elbow > forearm > hand
const ap=new THREE.Group();ap.position.set(sd*.335,1.56,0);ap.rotation.z=sd*-.08;upper.add(ap);
put(ap,sph(.082,jersey),0,0,0);put(ap,cyl(.074,.066,.19,jersey),0,-.09,0);put(ap,cyl(.052,.047,.15,H2?baseM:skin),0,-.22,0);
const el=new THREE.Group();el.position.y=-.3;el.rotation.x=-.35;ap.add(el);
put(el,sph(.046,H2?baseM:skin),0,0,0);put(el,cyl(.047,.037,.26,H2?baseM:skin),0,-.135,0);
const gl=number===1?mat(0xf2f2ea,.7):skin;put(el,sph(number===1?.058:.043,gl,.85,1.15,.8),0,-.29,.01);if(number===1)put(el,cyl(.05,.05,.04,mat(kit.j,.6)),0,-.245,0);
// leg: thigh > knee > shin (sock) > boot
const lp=new THREE.Group();lp.position.set(sd*.115,.93,0);body.add(lp);
put(lp,cyl(.11,.078,.44,skin),0,-.21,0);put(lp,cyl(.122,.134,.27,shorts),0,-.09,0);
const kn=new THREE.Group();kn.position.y=-.44;lp.add(kn);
put(kn,sph(.078,skin),0,0,0);put(kn,cyl(.076,.055,.42,sock),0,-.2,0);put(kn,sph(.07,sock,1,1.5,1),0,-.11,-.025);put(kn,cyl(.078,.078,.04,trim),0,-.03,0,false);if(H2)put(kn,cyl(.06,.058,.12,whiteM),0,-.36,0);
const ft=new THREE.Group();ft.position.set(0,-.41,.045);kn.add(ft);
const sh=new THREE.Mesh(new THREE.CapsuleGeometry(.048,.16,5,12),boot);sh.rotation.x=Math.PI/2;sh.scale.set(1.12,1,.78);put(ft,sh,0,-.03,.03);
put(ft,new THREE.Mesh(new THREE.BoxGeometry(.108,.018,.27),sole),0,-.07,.04,false);put(ft,new THREE.Mesh(new THREE.BoxGeometry(.016,.01,.14),bootAcc),0,.01,.05,false);
limbs.push({arm:ap,elbow:el,leg:lp,knee:kn,s:sd});
}
const shadow=new THREE.Mesh(new THREE.CircleGeometry(.43,24),new THREE.MeshBasicMaterial({color:0x07140a,transparent:true,opacity:.25}));shadow.rotation.x=-Math.PI/2;shadow.position.y=.018;root.add(shadow);
root.scale.setScalar(HGT[who]||1);root.userData={limbs,home,upper,body,gk:number===1};scene.add(root);return root;
}
function addNameTag(obj,name,color='#ffffff'){
const canvas=document.createElement('canvas');canvas.width=512;canvas.height=128;const c=canvas.getContext('2d');
c.fillStyle='rgba(5,16,12,.82)';c.beginPath();c.roundRect(12,12,488,104,22);c.fill();
c.strokeStyle=color;c.lineWidth=5;c.stroke();c.fillStyle=color;c.font='bold 48px Arial';c.textAlign='center';c.textBaseline='middle';c.fillText(name,256,66);
const tex=new THREE.CanvasTexture(canvas);tex.colorSpace=THREE.SRGBColorSpace;
const sprite=new THREE.Sprite(new THREE.SpriteMaterial({map:tex,transparent:true,depthTest:false}));sprite.scale.set(2.5,.62,1);sprite.position.set(0,2.65,0);obj.add(sprite);obj.userData.playerName=name;return obj;
}
const player=addNameTag(makePlayer(true,10,'star'),'MESSI','#c8ff38');player.position.set(0,0,20);
const teammates=[addNameTag(makePlayer(true,7,'mbappe'),'MBAPPÉ','#c8ff38'),addNameTag(makePlayer(true,11,'neymar'),'NEYMAR JR','#c8ff38')];teammates[0].position.set(-10,0,25);teammates[1].position.set(10,0,25);
const opponents=[addNameTag(makePlayer(false,7,'ronaldo'),'RONALDO','#ff6b6b'),addNameTag(makePlayer(false,9,'haaland'),'HAALAND','#ff6b6b'),addNameTag(makePlayer(false,11,'salah'),'SALAH','#ff6b6b'),addNameTag(makePlayer(false,7,'vini'),'VINÍCIUS JR','#ff6b6b')];
opponents[0].position.set(-10,0,-10);opponents[1].position.set(10,0,-8);opponents[2].position.set(0,0,-20);opponents[3].position.set(-2,0,0);
const homeRoster=[player,...teammates],oppRoster=[...opponents];homeRoster.concat(oppRoster).forEach(o=>{o.userData.start=o.position.clone();o.userData.off=false;o.userData.yellows=0});
function makeBall(){const group=new THREE.Group();
const map=cTex(512,256,(c,w,h)=>{c.fillStyle='#f6f6f0';c.fillRect(0,0,w,h);const t=(1+Math.sqrt(5))/2,V=[];for(const a of [-1,1])for(const b of [-1,1])V.push([0,a,b*t],[a,b*t,0],[b*t,0,a]);
const cr=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]],nm=a=>{const l=Math.hypot(...a);return a.map(q=>q/l)};c.fillStyle='#16191c';
V.forEach(v=>{const d=nm(v),u=nm(cr(Math.abs(d[1])>.9?[1,0,0]:[0,1,0],d)),w2=cr(d,u),P=[];for(let k=0;k<5;k++){const f=k*Math.PI*2/5,r=.36,p=[0,1,2].map(i=>d[i]*Math.cos(r)+(u[i]*Math.cos(f)+w2[i]*Math.sin(f))*Math.sin(r));let ph=Math.atan2(p[2],-p[0]);if(ph<0)ph+=Math.PI*2;P.push([ph/(Math.PI*2)*w,Math.acos(p[1])/Math.PI*h])}
for(let k=1;k<5;k++){while(P[k][0]-P[0][0]>w/2)P[k][0]-=w;while(P[0][0]-P[k][0]>w/2)P[k][0]+=w}
for(const o of [-w,0,w]){c.beginPath();P.forEach((q,k)=>k?c.lineTo(q[0]+o,q[1]):c.moveTo(q[0]+o,q[1]));c.closePath();c.fill()}})});
const ball=new THREE.Mesh(new THREE.SphereGeometry(.24,48,32),new THREE.MeshPhysicalMaterial({map,bumpMap:map,bumpScale:.25,roughness:.38,clearcoat:.5,clearcoatRoughness:.3}));ball.castShadow=true;ball.receiveShadow=true;group.add(ball);
const shadow=new THREE.Mesh(new THREE.CircleGeometry(.31,20),new THREE.MeshBasicMaterial({color:0x06140a,transparent:true,opacity:.33}));shadow.rotation.x=-Math.PI/2;shadow.position.y=-.20;group.add(shadow);scene.add(group);return group}
const ball=makeBall();ball.position.set(.7,.25,19.2);
const lastB=ball.position.clone(),axisB=new THREE.Vector3();
function rollBall(){const b=ball.position,mx=b.x-lastB.x,mz=b.z-lastB.z,dd=Math.hypot(mx,mz);if(dd>1e-4&&dd<3)ball.children[0].rotateOnWorldAxis(axisB.set(mz,0,-mx).normalize(),dd/.24);lastB.copy(b);const sh=ball.children[1],k=1+(b.y-.25)*.15;sh.position.y=-b.y+.02;sh.scale.set(k,k,1);sh.material.opacity=Math.max(.12,.33-(b.y-.25)*.06)}
// Goalkeeper: a dedicated keeper that slides across the goal mouth
const keeper=addNameTag(makePlayer(false,1,'courtois'),'COURTOIS','#ff6b6b');keeper.scale.set(.92,1.05,.92);keeper.position.set(0,0,-fl/2+1.3);
// Referee: black shorts and a bright referee shirt, positioned near play.
const referee=makePlayer(false,12,'ref');referee.position.set(0,0,0);referee.scale.set(.92,1,.92);
const keys={};let charge=0,charging=false,lastTouch='home';let controlledPlayer=player;let running=false,prev=performance.now(),clock=90,homeScore=0,awayScore=0,shotLock=0,passLock=0,flight=0,toastTimeout,enemyPossessor=null,enemyShotCooldown=0,keeperHasBall=false,keeperPassTimer=0,foulCooldown=0,foulCount=0,homeFouls=0,awayFouls=0,freeKickActive=false,freeKickTeam='home',yellowCards=0,redCards=0,slideTimer=0,slideCooldown=0;
function showMessage(t){const el=document.querySelector('#message');el.textContent=t;el.style.opacity=1;clearTimeout(toastTimeout);toastTimeout=setTimeout(()=>el.style.opacity=0,1700)}
let restartType='free';
const hintEl=()=>document.querySelector('#setPieceHint');
// Human restart (throw-in / goal kick / corner): game freezes, SPACE takes it
function startRestart(type,x,z,text){freeKickActive=true;freeKickTeam='home';restartType=type;flight=0;enemyPossessor=null;keeperHasBall=false;
ball.position.set(x,.25,z);ball.userData={vx:0,vy:0,vz:0};const sx=x>0?-1:1,sz=z>0?-1:1,cp=controlledPlayer;
cp.position.set(THREE.MathUtils.clamp(x+sx*(type==='throw'?.9:1.2),-fw/2+.5,fw/2-.5),0,THREE.MathUtils.clamp(z+(type==='throw'?0:sz*1.2),-fl/2+.5,fl/2-.5));
cp.rotation.y=Math.atan2(x-cp.position.x,z-cp.position.z);referee.position.set(x*.9,0,z*.9);
const h=hintEl();h.textContent={throw:'スローイン:SPACEで再開',goal:'ゴールキック:SPACEで再開',corner:'コーナーキック:SPACEで再開'}[type];h.style.display='block';showMessage(text)}
// Opponent restart: nearest opponent takes it immediately and plays on
function aiRestart(x,z,text){freeKickActive=false;hintEl().style.display='none';flight=0;keeperHasBall=false;
x=THREE.MathUtils.clamp(x,-fw/2+.5,fw/2-.5);z=THREE.MathUtils.clamp(z,-fl/2+.5,fl/2-.5);
if(opponents.length){const o=opponents.reduce((a,b)=>Math.hypot(a.position.x-x,a.position.z-z)<=Math.hypot(b.position.x-x,b.position.z-z)?a:b);
o.position.set(x,0,z);o.rotation.y=Math.atan2(-x*.3,fl/2-z);enemyPossessor=o;enemyShotCooldown=1.2;ball.position.set(x,.25,z);ball.userData={vx:0,vy:0,vz:0}}
showMessage(text)}
function startFreeKick(team, x, z, text='FOUL! FREE KICK'){
if(team==='away'){aiRestart(x,z,text);return}
restartType='free';hintEl().textContent='フリーキック:SPACEで再開';
freeKickActive=true;freeKickTeam=team;flight=0;enemyPossessor=null;keeperHasBall=false;
ball.position.set(THREE.MathUtils.clamp(x,-fw/2+2,fw/2-2),.25,THREE.MathUtils.clamp(z,-fl/2+2,fl/2-2));ball.userData={vx:0,vy:0,vz:0};
controlledPlayer.position.set(THREE.MathUtils.clamp(ball.position.x+1.2,-fw/2+1,fw/2-1),0,THREE.MathUtils.clamp(ball.position.z+1.2,-fl/2+1,fl/2-1));
referee.position.set(ball.position.x+.7,0,ball.position.z-.7);referee.rotation.y=Math.PI;
document.querySelector('#setPieceHint').style.display='block';showMessage(text);
}
function sendOff(o,team){o.userData.off=true;o.visible=false;o.position.set(0,-50,0);
if(team==='home'){const i=teammates.indexOf(o);if(i>=0)teammates.splice(i,1);if(controlledPlayer===o)controlledPlayer=teammates[0]||homeRoster.find(m=>!m.userData.off)}
else{const i=opponents.indexOf(o);if(i>=0)opponents.splice(i,1);if(enemyPossessor===o)enemyPossessor=null}}
function callFoul(team, x, z, severe=false){
foulCount++;foulCooldown=3.2;
if(team==='home')homeFouls++;else awayFouls++;
let card='';const fouls=team==='home'?homeFouls:awayFouls;
if(severe||fouls>=3||Math.random()<.22){
const o=team==='home'?controlledPlayer:opponents.reduce((a,b)=>Math.hypot(a.position.x-x,a.position.z-z)<=Math.hypot(b.position.x-x,b.position.z-z)?a:b);
let red=severe||fouls>=5,second=false;
if(!red){o.userData.yellows=(o.userData.yellows||0)+1;if(o.userData.yellows>=2){red=true;second=true}}
const canOff=team==='home'?homeRoster.filter(m=>!m.userData.off).length>1:opponents.length>1;
if(red&&canOff){redCards++;card=(second?' 🟨🟨 SECOND YELLOW':'')+' 🟥 RED CARD · '+(o.userData.playerName||'PLAYER')+' SENT OFF';sendOff(o,team)}
else{yellowCards++;card=' 🟨 YELLOW CARD'}
document.querySelector('#cardDisplay').innerHTML=`🟨 ${yellowCards} 🟥 ${redCards}`;
}
startFreeKick(team==='home'?'away':'home',x,z,`${team==='home'?'HOME':'AWAY'} FOUL${card} · FREE KICK`);
}
function resetPositions(){homeRoster.concat(oppRoster).forEach(o=>{if(!o.userData.off)o.position.copy(o.userData.start)});controlledPlayer=homeRoster.find(o=>!o.userData.off);const st=controlledPlayer.userData.start;ball.position.set(st.x+.7,.25,st.z-.8);ball.userData={};flight=0;enemyPossessor=null;enemyShotCooldown=0;keeperHasBall=false;keeperPassTimer=0;foulCooldown=0;foulCount=0;freeKickActive=false;document.querySelector('#setPieceHint').style.display='none';}
function restoreAll(){homeRoster.concat(oppRoster).forEach(o=>{o.userData.off=false;o.userData.yellows=0;o.visible=true});teammates.length=0;teammates.push(...homeRoster.slice(1));opponents.length=0;opponents.push(...oppRoster);yellowCards=redCards=homeFouls=awayFouls=0;document.querySelector('#cardDisplay').innerHTML=''}
function kickOff(){homeScore=awayScore=0;clock=90;document.querySelector('#homeScore').textContent='0';document.querySelector('#awayScore').textContent='0';document.querySelector('#clock').textContent='90:00';restoreAll();resetPositions();document.querySelector('.panel h1').innerHTML='OWN THE<br><span style="color:#c8ff38">PITCH.</span>';document.querySelector('.panel p').textContent='立体のピッチを走り、相手をかわしてゴールを狙おう。';document.querySelector('#start').textContent='KICK OFF →';running=true;document.querySelector('#overlay').style.display='none';prev=performance.now()}
document.querySelector('#start').addEventListener('click',kickOff);
window.addEventListener('keydown',e=>{const k=e.key.toLowerCase();if([' ','arrowup','arrowdown','arrowleft','arrowright'].includes(k))e.preventDefault();keys[k]=true});
window.addEventListener('keyup',e=>keys[e.key.toLowerCase()]=false);
document.querySelectorAll('[data-key]').forEach(b=>{const k=b.dataset.key;const down=e=>{e.preventDefault();keys[k]=true},up=e=>{e.preventDefault();keys[k]=false};b.addEventListener('pointerdown',down);b.addEventListener('pointerup',up);b.addEventListener('pointercancel',up);b.addEventListener('pointerleave',up)});
function animatePlayer(obj,t,speed){const {limbs,upper}=obj.userData;limbs.forEach((l,i)=>{const ph=t*10+i*Math.PI,sn=Math.sin(ph);l.leg.rotation.x=sn*speed*.6;l.knee.rotation.x=Math.max(0,Math.sin(ph+1.2))*speed*.95;l.arm.rotation.x=-sn*speed*.45;l.elbow.rotation.x=-(.35+Math.max(0,-sn)*speed*.5)});upper.rotation.y=Math.sin(t*10)*.1*speed;upper.rotation.x=.06*speed;upper.position.y=Math.abs(Math.cos(t*10))*.025*speed}
const wrapA=a=>Math.atan2(Math.sin(a),Math.cos(a));
// Procedural animation driven by real movement: stride follows distance travelled, bodies turn smoothly, kick / dive / slide poses
function animateAll(dt,t){if(!(dt>0))return;
for(const o of homeRoster.concat(oppRoster,[keeper,referee])){const u=o.userData;if(u.off||!u.limbs)continue;
if(u.lx===undefined){u.lx=o.position.x;u.lz=o.position.z;u.vis=o.rotation.y;u.ph=Math.random()*6;u.sp=0;u.kick=0;u.dive=0}
const dist=Math.hypot(o.position.x-u.lx,o.position.z-u.lz);u.lx=o.position.x;u.lz=o.position.z;
u.sp+=(Math.min(dist/dt,14)-u.sp)*(1-Math.exp(-9*dt));const amp=Math.min(u.sp/7,1.5);u.ph+=dist*2.1;
u.vis+=wrapA(o.rotation.y-u.vis)*(1-Math.exp(-14*dt));u.body.rotation.y=wrapA(u.vis-o.rotation.y);
u.kick=Math.max(0,u.kick-dt);u.dive=Math.max(0,u.dive-dt);
const rd=u.gk?Math.max(0,1-amp*2):0,k=u.kick>0?1-u.kick/.32:-1,dv=u.dive>0?1-u.dive/.6:-1,slide=o.rotation.x<-.1;
u.limbs.forEach((l,i)=>{const sn=Math.sin(u.ph+i*Math.PI);
l.leg.rotation.x=sn*amp*.7-rd*.3;l.knee.rotation.x=Math.max(0,Math.sin(u.ph+i*Math.PI+1.3))*.95*amp+.06+rd*.6;
l.arm.rotation.x=-sn*amp*.8;l.arm.rotation.z=l.s*-(.08+rd*.55);l.elbow.rotation.x=-(.2+amp*(.55+.35*Math.max(0,-sn))+rd*.3);
if(k>=0){if(i===1){l.leg.rotation.x=k<.4?k/.4*.9:.9-(k-.4)/.6*2.3;l.knee.rotation.x=k<.4?k/.4*1.1:Math.max(0,1.1*(1-(k-.4)/.35))}else{l.knee.rotation.x=.3;l.leg.rotation.x=.1}l.arm.rotation.z=l.s*-.6;l.arm.rotation.x=0}
if(dv>=0){l.arm.rotation.x=-2.7*Math.min(1,dv*4);l.arm.rotation.z=l.s*-.15;l.elbow.rotation.x=-.1}
if(slide){l.leg.rotation.x=i?-.6:-1.4;l.knee.rotation.x=i?.5:.2;l.arm.rotation.x=.8}});
u.upper.rotation.set(.04+amp*.12+rd*.12-(k>=0?Math.sin(k*Math.PI)*.12:0),Math.sin(u.ph)*.14*amp,0);
u.upper.position.y=Math.abs(Math.cos(u.ph))*.03*amp+Math.sin(t*2.3+u.ph)*.004;
u.body.position.y=-rd*.04+(dv>=0?Math.sin(dv*Math.PI)*.55:0);
u.body.rotation.z=dv>=0?-(u.ds||1)*Math.min(1,dv*3)*(dv>.75?(1-dv)*4:1)*1.1:0}}
function update(dt,t){
if(!running)return;
clock=Math.max(0,clock-dt);document.querySelector('#clock').textContent=`${Math.floor(clock)}:${String(Math.floor((clock%1)*60)).padStart(2,'0')}`;
if(clock<=0){running=false;document.querySelector('#overlay').style.display='flex';document.querySelector('.panel h1').innerHTML='FULL<br><span style="color:#c8ff38">TIME.</span>';document.querySelector('.panel p').textContent=`試合終了! スコア ${homeScore} - ${awayScore}。もう一度挑戦しよう。`;document.querySelector('#start').textContent='PLAY AGAIN →';return}
const activePlayer=controlledPlayer;const p=activePlayer.position;foulCooldown=Math.max(0,foulCooldown-dt);
if(freeKickActive){
charging=false;charge=0;document.querySelector('#powerBar').style.display='none';
referee.position.x=THREE.MathUtils.damp(referee.position.x,ball.position.x+.7,3,dt);referee.position.z=THREE.MathUtils.damp(referee.position.z,ball.position.z-.7,3,dt);
if(keys[' ']){keys[' ']=false;freeKickActive=false;document.querySelector('#setPieceHint').style.display='none';
const aim=(tx,tz,sp,vy,fs)=>{const vx=tx-ball.position.x,vz=tz-ball.position.z,vl=Math.hypot(vx,vz)||1;ball.userData.vx=vx/vl*sp;ball.userData.vz=vz/vl*sp;ball.userData.vy=vy;flight=fs};
lastTouch='home';shotLock=.7;
if(restartType==='throw'){let tgt=null,best=15;for(const m of teammates){if(m===controlledPlayer)continue;const dd=Math.hypot(m.position.x-ball.position.x,m.position.z-ball.position.z);if(dd<best){best=dd;tgt=m}}const sg=Math.sign(ball.position.x)||1;aim(tgt?tgt.position.x:ball.position.x-sg*9,tgt?tgt.position.z:ball.position.z-4,11,3.2,.95);showMessage('THROW-IN!')}
else if(restartType==='goal'){aim(0,-fl/2+24,24,7.5,1.7);controlledPlayer.userData.kick=.32;showMessage('GOAL KICK!')}
else if(restartType==='corner'){aim(0,-fl/2+9,17,7,1.5);controlledPlayer.userData.kick=.32;showMessage('CORNER KICK!')}
else{const goalZ=freeKickTeam==='home'?-fl/2-3:fl/2+3,aimX=THREE.MathUtils.clamp(-ball.position.x*.35,-2.7,2.7);aim(aimX,goalZ,19,6.2,1.5);controlledPlayer.userData.kick=.32;showMessage('FREE KICK!')}
}
const behind=new THREE.Vector3(-Math.sin(activePlayer.rotation.y)*2,0,Math.cos(activePlayer.rotation.y)*2);camera.position.lerp(new THREE.Vector3(p.x*.45+behind.x,9.5,p.z+13.5+behind.z),1-Math.exp(-3*dt));camera.lookAt(p.x*.25,.65,p.z-7.5);return;
}let dx=(keys.d||keys.arrowright?1:0)-(keys.a||keys.arrowleft?1:0),dz=(keys.s||keys.arrowdown?1:0)-(keys.w||keys.arrowup?1:0),len=Math.hypot(dx,dz);if(len){dx/=len;dz/=len}
slideCooldown=Math.max(0,slideCooldown-dt);slideTimer=Math.max(0,slideTimer-dt);
const speed=slideTimer>0?13.5:(keys.shift?10.5:7.1);p.x+=dx*speed*dt;p.z+=dz*speed*dt;p.x=THREE.MathUtils.clamp(p.x,-fw/2+1,fw/2-1);p.z=THREE.MathUtils.clamp(p.z,-fl/2+1,fl/2-1);
if(len){activePlayer.rotation.y=Math.atan2(dx,dz);animatePlayer(activePlayer,t,keys.shift?1.5:1)}
// C: sliding tackle. Burst forward and attempt to dispossess a nearby opponent.
if(keys.c&&slideCooldown<=0&&!freeKickActive){
keys.c=false;slideTimer=.42;slideCooldown=1.15;
const sx=Math.sin(activePlayer.rotation.y),sz=Math.cos(activePlayer.rotation.y);
p.x=THREE.MathUtils.clamp(p.x+sx*1.15,-fw/2+1,fw/2-1);p.z=THREE.MathUtils.clamp(p.z+sz*1.15,-fl/2+1,fl/2-1);
let victim=null,bestDist=2.65;for(const o of opponents){const od=Math.hypot(o.position.x-p.x,o.position.z-p.z);if(od<bestDist){bestDist=od;victim=o}}
if(victim){
const wasPossessing=enemyPossessor===victim;
if(Math.random()<.24){if(foulCooldown<=0)callFoul('home',victim.position.x,victim.position.z+.5,Math.random()<.35);showMessage('SLIDE FOUL!');}
else {enemyPossessor=null;flight=0;ball.position.set(victim.position.x,.25,victim.position.z+.65);ball.userData.vx=sx*4;ball.userData.vz=sz*4;showMessage(wasPossessing?'SLIDE TACKLE! BALL WON!':'SLIDE CHALLENGE!');}
} else {showMessage('SLIDE TACKLE!');}
}
if(slideTimer>0){activePlayer.rotation.x=-.35;animatePlayer(activePlayer,t,1.8)}else{activePlayer.rotation.x=0;}
// Ball follows in front of player unless kicked
shotLock=Math.max(0,shotLock-dt);passLock=Math.max(0,passLock-dt);
const d=Math.hypot(ball.position.x-p.x,ball.position.z-p.z);if(enemyPossessor||keeperHasBall)lastTouch='away';else if(flight<=0&&d<2.0)lastTouch='home';
if(flight>0){flight-=dt;ball.position.x+=ball.userData.vx*dt;ball.position.z+=ball.userData.vz*dt;ball.position.y=Math.max(.24,ball.position.y+ball.userData.vy*dt);ball.userData.vy-=14*dt;
if(ball.position.y<=.25){ball.position.y=.25;ball.userData.vy=Math.abs(ball.userData.vy)*.3;if(Math.abs(ball.userData.vy)<1.4)ball.userData.vy=0}
ball.userData.vx*=Math.pow(.55,dt);ball.userData.vz*=Math.pow(.55,dt);
}else if(!enemyPossessor&&d<2.0){const front=new THREE.Vector3(Math.sin(activePlayer.rotation.y),0,Math.cos(activePlayer.rotation.y));const target=p.clone().add(front.multiplyScalar(.95));ball.position.x=THREE.MathUtils.damp(ball.position.x,target.x,8,dt);ball.position.z=THREE.MathUtils.damp(ball.position.z,target.z,8,dt);ball.position.y=.25;}
else {ball.position.x+=(ball.userData.vx||0)*dt;ball.position.z+=(ball.userData.vz||0)*dt;ball.userData.vx=(ball.userData.vx||0)*Math.pow(.18,dt);ball.userData.vz=(ball.userData.vz||0)*Math.pow(.18,dt)}
// Pass to the nearest teammate, with a grounded, fast ball trajectory
if(keys.e&&passLock<=0&&d<2.8&&flight<=0&&!enemyPossessor&&teammates.length>0){
let target=teammates[0],best=Infinity;for(const mate of teammates){const md=mate.position.distanceTo(p);if(md<best){best=md;target=mate}}
// Offside: receiver is beyond the ball and the second-last defender toward the opponent goal (-Z).
const defenders=[...opponents].sort((a,b)=>a.position.z-b.position.z);const secondLast=defenders[1];
if(target.position.z<p.z-.2&&secondLast&&target.position.z<secondLast.position.z-.15){
keys.e=false;startFreeKick('away',target.position.x,target.position.z,'OFFSIDE! FREE KICK TO OPPONENT');return;
}
const lead=keys.shift?4:0;const vx=target.position.x+Math.sign(target.position.x-p.x)*lead-ball.position.x,vz=target.position.z+(keys.shift?-5:0)-ball.position.z,vl=Math.hypot(vx,vz)||1;
ball.userData.vx=vx/vl*(keys.shift?19:15);ball.userData.vz=vz/vl*(keys.shift?19:15);ball.userData.vy=keys.shift?2.8:1.8;flight=Math.max(.35,vl/(keys.shift?19:15));shotLock=.25;passLock=.65;keys.e=false;lastTouch='home';controlledPlayer.userData.kick=.28;controlledPlayer=target;showMessage('PASS! · PLAYER SWITCH');
}
// Opponents now build attacks: press, win possession, dribble forward, and shoot
enemyShotCooldown=Math.max(0,enemyShotCooldown-dt);
if(enemyPossessor){
const e=enemyPossessor;
// User can tackle and win the ball back by getting close
if(Math.hypot(e.position.x-p.x,e.position.z-p.z)<1.25){
enemyPossessor=null;flight=0;ball.userData.vx=0;ball.userData.vz=0;
// A mistimed tackle can be called as a foul; otherwise it is a clean tackle.
if(foulCooldown<=0&&Math.random()<(keys.shift?.28:.14)){callFoul('home',e.position.x,e.position.z+.8,keys.shift&&Math.random()<.25)}
else {showMessage('TACKLE!');}
}
else {
const goalX=THREE.MathUtils.clamp(-e.position.x*.28,-2.7,2.7),goalZ=fl/2-1.2;
const ax=goalX-e.position.x,az=goalZ-e.position.z,al=Math.hypot(ax,az)||1;
e.position.x+=ax/al*4.0*dt;e.position.z+=az/al*4.0*dt;e.rotation.y=Math.atan2(ax,az);animatePlayer(e,t,1.05);
ball.position.x=e.position.x+Math.sin(e.rotation.y)*.85;ball.position.z=e.position.z+Math.cos(e.rotation.y)*.85;ball.position.y=.25;flight=0;
if(e.position.z>fl/2-18&&enemyShotCooldown<=0){const tx=THREE.MathUtils.clamp(-ball.position.x*.22,-2.4,2.4);const vx=tx-ball.position.x,vz=fl/2+3-ball.position.z,vl=Math.hypot(vx,vz)||1;ball.userData.vx=vx/vl*17;ball.userData.vz=vz/vl*17;ball.userData.vy=3.1;flight=1.35;enemyPossessor=null;enemyShotCooldown=2.4;e.userData.kick=.32;showMessage('OPPONENT SHOT!');}
}
}
opponents.forEach((o,i)=>{
if(enemyPossessor===o)return;
const ox=ball.position.x-o.position.x,oz=ball.position.z-o.position.z,od=Math.hypot(ox,oz);
// One defender hunts the ball; others spread into attacking lanes when their team has possession
let tx=ball.position.x,tz=ball.position.z;
if(enemyPossessor){tx=ball.position.x+(i-1.5)*4;tz=ball.position.z-5+Math.abs(i-1.5)*1.5;}
const vx=tx-o.position.x,vz=tz-o.position.z,vl=Math.hypot(vx,vz)||1;
if(vl>.9){o.position.x+=vx/vl*(i===0?4.0:2.8)*dt;o.position.z+=vz/vl*(i===0?4.0:2.8)*dt;o.rotation.y=Math.atan2(vx,vz);animatePlayer(o,t,.8)}
if(od<1.25&&flight<=0&&d>1.4){enemyPossessor=o;ball.userData.vx=0;ball.userData.vz=0;ball.position.x=o.position.x;ball.position.z=o.position.z+.7;showMessage('THEY HAVE THE BALL!')}
});
// Opponents can also commit contact fouls when challenging the controlled player.
if(foulCooldown<=0&&flight<=0&&!enemyPossessor&&d<2.3){
for(const o of opponents){
const contact=Math.hypot(o.position.x-p.x,o.position.z-p.z);
if(contact<1.0&&Math.random()<.035){
callFoul('away',p.x+Math.sin(activePlayer.rotation.y)*.9,p.z+Math.cos(activePlayer.rotation.y)*.9,Math.random()<.08);break;
}
}
}
// Keeper reads the ball and shuffles laterally, then blocks shots near goal
// Make the goalkeeper much weaker: very slow reactions and a tiny save zone.
const keeperTarget=THREE.MathUtils.clamp(ball.position.x,-1.8,1.8);
keeper.position.x=THREE.MathUtils.damp(keeper.position.x,keeperTarget,.55,dt);
// Keep the goalkeeper's head and body orientation stable; only shuffle laterally.
keeper.rotation.y=0;
animatePlayer(keeper,t,.08);
if(flight>0&&ball.position.z< -fl/2+4.2&&ball.position.z> -fl/2-0.8&&Math.abs(ball.position.x-keeper.position.x)<0.28&&ball.position.y<1.1){
// Keeper catches/controls the ball, then distributes it to a teammate.
ball.position.set(keeper.position.x,.25,keeper.position.z+1.0);
ball.userData.vx=0;ball.userData.vz=0;ball.userData.vy=0;flight=0;
keeperHasBall=true;keeperPassTimer=.65;keeper.userData.dive=.6;keeper.userData.ds=Math.random()<.5?-1:1;showMessage('KEEPER SAVE!');
}
if(keeperHasBall){
ball.position.x=keeper.position.x;ball.position.y=.25;ball.position.z=keeper.position.z+1.0;
keeperPassTimer-=dt;
if(keeperPassTimer<=0){
let target=teammates[0],best=Infinity;
for(const mate of homeRoster.filter(o=>!o.userData.off)){const md=mate.position.distanceTo(keeper.position);if(md<best){best=md;target=mate}}
const vx=target.position.x-ball.position.x, vz=target.position.z-ball.position.z,vl=Math.hypot(vx,vz)||1;
ball.userData.vx=vx/vl*15;ball.userData.vz=vz/vl*15;ball.userData.vy=2.0;flight=Math.max(.4,vl/15);
keeperHasBall=false;keeper.userData.kick=.3;showMessage('KEEPER PASS!');
}
}
// Teammates move into open support positions
teammates.forEach((o,i)=>{if(o===controlledPlayer)return;const tx=THREE.MathUtils.clamp(p.x+(i===0?-8:8),-fw/2+2,fw/2-2),tz=THREE.MathUtils.clamp(p.z+5,-fl/2+2,fl/2-2);o.position.x=THREE.MathUtils.damp(o.position.x,tx,.8,dt);o.position.z=THREE.MathUtils.damp(o.position.z,tz,.8,dt);animatePlayer(o,t,.3)});
// Skill moves: Q performs a quick feint burst with a close touch; F performs a sharp cut.
if((keys.q||keys.f)&&shotLock<=0&&d<2.7&&!enemyPossessor&&flight<=0){
const turn=keys.f?-.95:.65; const facing=activePlayer.rotation.y+turn;
activePlayer.rotation.y=facing;
const nx=Math.sin(facing),nz=Math.cos(facing);
ball.position.x=p.x+nx*1.05;ball.position.z=p.z+nz*1.05;ball.position.y=.25;
ball.userData.vx=nx*(keys.shift?8:5.5);ball.userData.vz=nz*(keys.shift?8:5.5);flight=.18;shotLock=.42;
lastTouch='home';keys.q=false;keys.f=false;showMessage(turn>0?'SKILL MOVE!':'CUT & GO!');
}
// Chip / lob shot: a high, arcing attempt toward the opponent goal.
if(keys.r&&shotLock<=0&&d<2.8&&!enemyPossessor&&flight<=0){
ball.userData.vx=THREE.MathUtils.clamp(-ball.position.x*.75,-3.5,3.5);ball.userData.vz=-16;ball.userData.vy=8.5;flight=1.65;shotLock=.65;keys.r=false;lastTouch='home';controlledPlayer.userData.kick=.32;showMessage('CHIP SHOT!');
}
// Through ball: hold E with Shift to send the pass into space rather than directly to feet.
// Shoot in direction of the opponent's goal, with slight aim toward center
const canShoot=shotLock<=0&&d<2.5&&!enemyPossessor;
if(keys[' ']&&canShoot){charging=true;charge=Math.min(1,charge+dt/.9)}
else{
if(charging&&!keys[' ']&&canShoot){
const pw=Math.max(.2,charge),spread=pw>.85?(Math.random()-.5)*(pw-.85)*20:0;
ball.userData.vx=THREE.MathUtils.clamp(-ball.position.x*1.2,-4,4)*(.5+pw*.5)+spread;ball.userData.vz=-(12+36*pw);ball.userData.vy=3+3*pw;flight=1.1+.6*pw;shotLock=.55;
lastTouch='home';controlledPlayer.userData.kick=.32;showMessage(pw<.4?'SOFT SHOT':pw>.85?'POWER SHOT!':'SHOT!');
}
charging=false;charge=0;
}
document.querySelector('#powerBar').style.display=charging?'block':'none';document.querySelector('#powerFill').style.width=(charge*100)+'%';
// Goal if ball passes into goal mouth at the far end
if(ball.position.z< -fl/2-.4&&Math.abs(ball.position.x)<3.8&&ball.position.y<2.6){homeScore++;document.querySelector('#homeScore').textContent=homeScore;crowdBoost=.4;showMessage('GOAL!');resetPositions()}
if(ball.position.z>fl/2+.4&&Math.abs(ball.position.x)<3.8&&ball.position.y<2.6){awayScore++;document.querySelector('#awayScore').textContent=awayScore;crowdBoost=.25;showMessage('GOAL');resetPositions()}
if(!keeperHasBall&&!enemyPossessor){const bx=ball.position.x,bz=ball.position.z,gm=Math.abs(bx)<3.8;
if(Math.abs(bx)>fw/2){const hz=THREE.MathUtils.clamp(bz,-fl/2+1,fl/2-1),tx=Math.sign(bx)*(fw/2-.2);
if(lastTouch==='home')aiRestart(tx,hz,'THROW-IN · OPPONENT');else startRestart('throw',tx,hz,'THROW-IN')}
else if(Math.abs(bz)>fl/2+(gm?.4:0)){const es=Math.sign(bz),att=es<0?'home':'away';
if(lastTouch===att){if(es<0)aiRestart(0,-fl/2+5.5,'GOAL KICK · OPPONENT');else startRestart('goal',0,fl/2-5.5,'GOAL KICK')}
else{const cx=(bx>=0?1:-1)*(fw/2-.3),cz=es*(fl/2-.3);if(att==='home')startRestart('corner',cx,cz,'CORNER KICK');else aiRestart(cx,cz,'CORNER · OPPONENT')}}}
referee.position.x=THREE.MathUtils.damp(referee.position.x,ball.position.x+2.5,1.2,dt);referee.position.z=THREE.MathUtils.damp(referee.position.z,ball.position.z+1.5,1.2,dt);referee.rotation.y=Math.atan2(ball.position.x-referee.position.x,ball.position.z-referee.position.z);animatePlayer(referee,t,.35);
// Camera follows player from behind and slightly above
const behind=new THREE.Vector3(-Math.sin(activePlayer.rotation.y)*2,0,Math.cos(activePlayer.rotation.y)*2);const desired=new THREE.Vector3(p.x*.45+behind.x,9.5,p.z+13.5+behind.z);camera.position.lerp(desired,1-Math.exp(-3*dt));camera.lookAt(p.x*.25,0.65,p.z-7.5);
}
function loop(now){requestAnimationFrame(loop);const dt=Math.min((now-prev)/1000,.035);prev=now;update(dt,now/1000);rollBall();animateAll(dt,now/1000);venueTick(dt,now/1000);renderer.render(scene,camera)}
window.addEventListener('resize',()=>{camera.aspect=innerWidth/innerHeight;camera.updateProjectionMatrix();renderer.setSize(innerWidth,innerHeight);renderer.setPixelRatio(Math.min(devicePixelRatio,2))});
camera.position.set(0,11,35);camera.lookAt(0,0,0);requestAnimationFrame(loop);
</script>
</body></html>
サッカーゲーム