-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspirit-gun.js
More file actions
486 lines (407 loc) · 15.3 KB
/
Copy pathspirit-gun.js
File metadata and controls
486 lines (407 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// Spirit Gun - Rei Gun Implementation
class SpiritGun {
constructor() {
this.video = document.getElementById('video');
this.canvas = document.getElementById('effectsCanvas');
this.ctx = this.canvas.getContext('2d');
// UI Elements
this.energyFill = document.getElementById('energyFill');
this.statusText = document.getElementById('statusText');
this.fireIndicator = document.getElementById('fireIndicator');
this.loadingScreen = document.getElementById('loadingScreen');
// State
this.hands = null;
this.camera = null;
this.isRunning = false;
this.fingerGunActive = false;
this.fingerTip = null;
this.aimDirection = { x: 1, y: 0 }; // smoothed aim vector
this.previousThumbY = null;
this.thumbWasUp = false;
this.energy = 100;
this.bullets = [];
this.particles = [];
this.lastShotTime = 0;
this.energyRecharging = false;
// Thumb detection smoothing/state
this.thumbAngle = null; // instantaneous angle (radians) between index direction and thumb vector
this.thumbAngleSmoothed = null; // EMA smoothed angle
this.thumbCocked = false; // hysteresis: "ready to fire" state
this.audioContext = null; // reused AudioContext
this.init();
}
async init() {
try {
// Initialize hand tracking
await this.initHandTracking();
// Start camera
await this.startCamera();
// Hide loading screen
setTimeout(() => {
this.loadingScreen.style.opacity = '0';
setTimeout(() => {
this.loadingScreen.style.display = 'none';
}, 500);
}, 1000);
} catch (error) {
console.error('Initialization failed:', error);
alert('Could not access camera. Please grant permissions.');
}
}
async initHandTracking() {
this.hands = new Hands({
locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/hands/${file}`;
}
});
this.hands.setOptions({
maxNumHands: 1,
modelComplexity: 0,
minDetectionConfidence: 0.7,
minTrackingConfidence: 0.7
});
this.hands.onResults((results) => this.onHandResults(results));
}
async startCamera() {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
width: { ideal: 1280 },
height: { ideal: 720 },
facingMode: 'user'
}
});
this.video.srcObject = stream;
await new Promise((resolve) => {
this.video.onloadedmetadata = () => {
this.video.play();
resolve();
};
});
// Setup canvas
this.resizeCanvas();
window.addEventListener('resize', () => this.resizeCanvas());
// Start render loop
this.isRunning = true;
this.render();
this.updateEnergy();
// Start hand tracking
this.camera = new Camera(this.video, {
onFrame: async () => {
await this.hands.send({ image: this.video });
},
width: 1280,
height: 720
});
this.camera.start();
}
onHandResults(results) {
if (!results.multiHandLandmarks || results.multiHandLandmarks.length === 0) {
this.fingerGunActive = false;
this.statusText.textContent = 'Form finger gun (thumb up = ready)';
this.statusText.classList.remove('ready');
this.previousThumbY = null;
this.thumbWasUp = false;
return;
}
const landmarks = results.multiHandLandmarks[0];
const isFingerGun = this.detectFingerGun(landmarks);
if (isFingerGun) {
this.fingerGunActive = true;
// Get fingertip position
const indexTip = landmarks[8];
// const indexMiddle = landmarks[7]; // not needed; keep for potential future direction math
// Convert to screen coordinates
this.fingerTip = {
x: indexTip.x * this.canvas.width,
y: indexTip.y * this.canvas.height,
z: indexTip.z
};
// Calculate direction vector (from index base to tip)
const indexBase = landmarks[5];
let dx = indexTip.x - indexBase.x;
let dy = indexTip.y - indexBase.y;
let dz = (indexTip.z || 0) - (indexBase.z || 0);
let length = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;
const dirX = dx / length;
const dirY = dy / length;
const dirZ = dz / length;
// Smooth the direction to reduce jitter (exponential moving average)
const smoothFactor = 0.7; // higher = smoother
this.aimDirection.x = smoothFactor * this.aimDirection.x + (1 - smoothFactor) * dirX;
this.aimDirection.y = smoothFactor * this.aimDirection.y + (1 - smoothFactor) * dirY;
// Re-normalize
const aimLen = Math.hypot(this.aimDirection.x, this.aimDirection.y) || 1;
this.aimDirection.x /= aimLen;
this.aimDirection.y /= aimLen;
// Thumb hammer motion using 3D angle with hysteresis
const thumbTip = landmarks[4];
const tdx = thumbTip.x - indexBase.x;
const tdy = thumbTip.y - indexBase.y;
const tdz = (thumbTip.z || 0) - (indexBase.z || 0);
const tlen = Math.sqrt(tdx * tdx + tdy * tdy + tdz * tdz) || 1;
const tdirX = tdx / tlen;
const tdirY = tdy / tlen;
const tdirZ = tdz / tlen;
const dot = Math.max(-1, Math.min(1, dirX * tdirX + dirY * tdirY + dirZ * tdirZ));
this.thumbAngle = Math.acos(dot);
const angleSmooth = 0.6;
this.thumbAngleSmoothed = this.thumbAngleSmoothed == null
? this.thumbAngle
: angleSmooth * this.thumbAngleSmoothed + (1 - angleSmooth) * this.thumbAngle;
// Hysteresis thresholds (radians) - computed but cocking uses robust vertical check
const COCK_THRESHOLD = 1.0; // ~57° (not required for cocking)
const FIRE_THRESHOLD = 0.6; // ~34° (not required for firing)
// Cock when thumb is visibly above index base
const cockCandidate = thumbTip.y < indexBase.y - 0.02;
if (!this.thumbCocked && cockCandidate && this.energy >= 20) {
this.thumbCocked = true;
}
if (this.energy < 20) {
this.statusText.textContent = 'Recharging...';
this.statusText.classList.remove('ready');
} else if (this.thumbCocked) {
this.statusText.textContent = 'Hammer cocked - drop thumb to fire!';
this.statusText.classList.add('ready');
} else {
this.statusText.textContent = 'Raise thumb to cock hammer';
this.statusText.classList.remove('ready');
}
// Generate ambient particles around finger
if (Math.random() < 0.3) {
this.createAmbientParticle(this.fingerTip.x, this.fingerTip.y);
}
// Fire when cocked and thumb moves downward past index base level
if (this.previousThumbY !== undefined && this.thumbCocked) {
const thumbDelta = thumbTip.y - this.previousThumbY;
if (thumbDelta > 0.015 && thumbTip.y > indexBase.y - 0.01) {
this.fire();
this.thumbCocked = false;
}
}
this.previousThumbY = thumbTip.y;
this.thumbWasUp = this.thumbCocked;
} else {
this.fingerGunActive = false;
this.statusText.textContent = 'Form finger gun (thumb up = ready)';
this.statusText.classList.remove('ready');
this.previousThumbY = null;
this.thumbWasUp = false;
this.thumbCocked = false;
this.thumbAngle = null;
this.thumbAngleSmoothed = null;
}
}
detectFingerGun(landmarks) {
const wrist = landmarks[0];
const thumb = { tip: landmarks[4], base: landmarks[2] };
const index = { tip: landmarks[8], base: landmarks[5] };
const middle = { tip: landmarks[12], base: landmarks[9] };
const ring = { tip: landmarks[16], base: landmarks[13] };
const pinky = { tip: landmarks[20], base: landmarks[17] };
// Index finger must be extended (the barrel)
const indexExtended = this.getDistance(wrist, index.tip) > this.getDistance(wrist, index.base) * 1.3;
// Thumb should be visible and somewhat extended (can be up or down)
const thumbVisible = this.getDistance(wrist, thumb.tip) > this.getDistance(wrist, thumb.base) * 0.8;
// Other fingers must be curled (closed fist)
const middleCurled = this.getDistance(wrist, middle.tip) < this.getDistance(wrist, middle.base) * 1.2;
const ringCurled = this.getDistance(wrist, ring.tip) < this.getDistance(wrist, ring.base) * 1.2;
const pinkyCurled = this.getDistance(wrist, pinky.tip) < this.getDistance(wrist, pinky.base) * 1.2;
return indexExtended && thumbVisible && middleCurled && ringCurled && pinkyCurled;
}
getDistance(point1, point2) {
const dx = point2.x - point1.x;
const dy = point2.y - point1.y;
const dz = (point2.z || 0) - (point1.z || 0);
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
fire() {
const now = Date.now();
if (now - this.lastShotTime < 300) return; // Cooldown
if (this.energy < 20) return; // Not enough energy
if (!this.fingerTip || !this.aimDirection) return;
this.lastShotTime = now;
this.energy = Math.max(0, this.energy - 20);
this.energyRecharging = true;
// Create bullet (spawn slightly ahead of fingertip along aim)
const spawnOffset = 25; // pixels ahead of fingertip
const bulletSpeed = 18; // pixels per frame
const bullet = {
x: this.fingerTip.x + this.aimDirection.x * spawnOffset,
y: this.fingerTip.y + this.aimDirection.y * spawnOffset,
vx: this.aimDirection.x * bulletSpeed,
vy: this.aimDirection.y * bulletSpeed,
size: 15,
life: 1.0,
trail: []
};
this.bullets.push(bullet);
// Muzzle flash effect
for (let i = 0; i < 20; i++) {
const angle = (Math.PI * 2 * i) / 20;
const speed = Math.random() * 3 + 2;
this.createParticle(
this.fingerTip.x,
this.fingerTip.y,
Math.cos(angle) * speed,
Math.sin(angle) * speed,
10,
{ r: 100, g: 150, b: 255 }
);
}
// Flash UI
this.fireIndicator.classList.add('active');
setTimeout(() => {
this.fireIndicator.classList.remove('active');
}, 200);
// Play sound (simple Web Audio API)
this.playShootSound();
}
playShootSound() {
if (!this.audioContext) {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
const audioContext = this.audioContext;
// Create whoosh sound
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(200, audioContext.currentTime + 0.3);
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.3);
}
createParticle(x, y, vx, vy, size, color) {
this.particles.push({
x, y, vx, vy, size,
life: 1.0,
color: color || { r: 100, g: 200, b: 255 }
});
}
createAmbientParticle(x, y) {
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 1 + 0.5;
this.createParticle(
x + (Math.random() - 0.5) * 30,
y + (Math.random() - 0.5) * 30,
Math.cos(angle) * speed,
Math.sin(angle) * speed,
3,
{ r: 100, g: 180, b: 255 }
);
}
updateEnergy() {
if (this.energyRecharging && this.energy < 100) {
this.energy = Math.min(100, this.energy + 0.5);
if (this.energy >= 100) {
this.energyRecharging = false;
}
}
this.energyFill.style.width = this.energy + '%';
setTimeout(() => this.updateEnergy(), 50);
}
render() {
if (!this.isRunning) return;
// Clear canvas
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// Update and draw bullets
this.bullets = this.bullets.filter(bullet => {
// Update position
bullet.x += bullet.vx;
bullet.y += bullet.vy;
bullet.life -= 0.01;
// Add trail point
bullet.trail.push({ x: bullet.x, y: bullet.y });
if (bullet.trail.length > 20) bullet.trail.shift();
// Check if out of bounds or expired
if (bullet.life <= 0 ||
bullet.x < -50 || bullet.x > this.canvas.width + 50 ||
bullet.y < -50 || bullet.y > this.canvas.height + 50) {
// Create impact effect
this.createImpact(bullet.x, bullet.y);
return false;
}
// Draw trail
this.ctx.strokeStyle = `rgba(100, 180, 255, ${bullet.life * 0.5})`;
this.ctx.lineWidth = bullet.size * 0.5;
this.ctx.lineCap = 'round';
this.ctx.beginPath();
bullet.trail.forEach((point, i) => {
if (i === 0) {
this.ctx.moveTo(point.x, point.y);
} else {
this.ctx.lineTo(point.x, point.y);
}
});
this.ctx.stroke();
// Draw bullet
const gradient = this.ctx.createRadialGradient(
bullet.x, bullet.y, 0,
bullet.x, bullet.y, bullet.size
);
gradient.addColorStop(0, `rgba(255, 255, 255, ${bullet.life})`);
gradient.addColorStop(0.3, `rgba(150, 200, 255, ${bullet.life})`);
gradient.addColorStop(1, `rgba(50, 100, 255, ${bullet.life * 0.5})`);
this.ctx.fillStyle = gradient;
this.ctx.beginPath();
this.ctx.arc(bullet.x, bullet.y, bullet.size, 0, Math.PI * 2);
this.ctx.fill();
// Outer glow
this.ctx.strokeStyle = `rgba(100, 200, 255, ${bullet.life * 0.3})`;
this.ctx.lineWidth = 3;
this.ctx.stroke();
return true;
});
// Update and draw particles
this.particles = this.particles.filter(particle => {
particle.x += particle.vx;
particle.y += particle.vy;
particle.life -= 0.02;
particle.size *= 0.98;
if (particle.life <= 0) return false;
this.ctx.fillStyle = `rgba(${particle.color.r}, ${particle.color.g}, ${particle.color.b}, ${particle.life})`;
this.ctx.beginPath();
this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
this.ctx.fill();
return true;
});
// Draw finger glow when active
if (this.fingerGunActive && this.fingerTip) {
const glowGradient = this.ctx.createRadialGradient(
this.fingerTip.x, this.fingerTip.y, 0,
this.fingerTip.x, this.fingerTip.y, 30
);
glowGradient.addColorStop(0, 'rgba(100, 200, 255, 0.6)');
glowGradient.addColorStop(1, 'rgba(100, 200, 255, 0)');
this.ctx.fillStyle = glowGradient;
this.ctx.beginPath();
this.ctx.arc(this.fingerTip.x, this.fingerTip.y, 30, 0, Math.PI * 2);
this.ctx.fill();
}
requestAnimationFrame(() => this.render());
}
createImpact(x, y) {
// Create explosion particles
for (let i = 0; i < 30; i++) {
const angle = (Math.PI * 2 * i) / 30;
const speed = Math.random() * 8 + 4;
this.createParticle(
x, y,
Math.cos(angle) * speed,
Math.sin(angle) * speed,
Math.random() * 6 + 3,
{ r: 100 + Math.random() * 100, g: 180, b: 255 }
);
}
}
resizeCanvas() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
}
// Initialize
window.addEventListener('load', () => {
new SpiritGun();
});