-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathportalEntity.js
More file actions
680 lines (571 loc) · 27.5 KB
/
Copy pathportalEntity.js
File metadata and controls
680 lines (571 loc) · 27.5 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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
/**
* PortalEntity class
* Represents an interactive portal that can teleport the player to an external URL
*/
import { Entity } from './entity.js';
import assetLoader from './assetLoader.js';
import { input } from './input.js';
import { debug } from './utils.js';
export class PortalEntity extends Entity {
/**
* Create a new portal entity
* @param {number} x - X position in the grid
* @param {number} y - Y position in the grid
* @param {number} z - Z position in the grid
* @param {Object} options - Portal options
*/
constructor(x, y, z = 0, options = {}) {
super(x, y, z);
// Set entity properties
this.type = 'portal';
this.isStatic = true;
this.collidable = true;
this.velocityX = 0;
this.velocityY = 0;
this.zHeight = 1.0;
// Portal-specific properties
this.portalId = options.id || 'portal1';
this.targetUrl = options.targetUrl || 'https://x.com/aialchemistart';
this.glowColor = options.glowColor || '#8A2BE2'; // BlueViolet glow
this.glowIntensity = 0.6; // Initial glow intensity (0-1)
this.glowDirection = 1; // Direction of glow animation (1 = increasing, -1 = decreasing)
this.glowSpeed = 0.03; // Speed of pulsing glow effect
this.maxGlowIntensity = 1.0;
this.minGlowIntensity = 0.3;
this.interactionDistance = options.interactionDistance || 4.0; // 3 grid units
// Interaction state
this.isPlayerNearby = false;
this.showPrompt = false;
this.interactionEnabled = true;
this.interactionPromptAlpha = 0; // For fade in/out effect
this.wasEnterPressed = false;
// Animation properties
this.animationTime = 0;
// Load portal image
this.loadPortalImage();
}
/**
* Load the portal image
*/
loadPortalImage() {
// Check if we already have this asset loaded
if (assetLoader.assets[this.portalId]) {
console.log(`PortalEntity: Portal image already loaded for ${this.portalId}`);
return;
}
console.log(`PortalEntity: Loading portal image for ${this.portalId}`);
// Create an image and set up loading
const img = new Image();
img.onload = () => {
console.log(`PortalEntity: Successfully loaded portal image for ${this.portalId}`);
assetLoader.assets[this.portalId] = img;
};
img.onerror = () => {
console.error(`PortalEntity: Failed to load portal image for ${this.portalId}`);
// Create a fallback canvas image
this.createFallbackImage();
};
// Set the source path to the portal image
const path = `assets/decor/Portal_1.png`;
console.log(`PortalEntity: Setting image src to: ${path}`);
img.src = path;
}
/**
* Create a fallback canvas-based image for the portal
*/
createFallbackImage() {
console.log('PortalEntity: Creating fallback canvas image');
// Create a canvas to generate an image
const canvas = document.createElement('canvas');
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext('2d');
// Draw a mystical portal
// Portal base
ctx.fillStyle = '#2E2E42';
ctx.beginPath();
ctx.arc(64, 64, 50, 0, Math.PI * 2);
ctx.fill();
// Portal glow
const gradient = ctx.createRadialGradient(64, 64, 10, 64, 64, 50);
gradient.addColorStop(0, '#8A2BE2'); // BlueViolet center
gradient.addColorStop(1, 'rgba(138, 43, 226, 0)'); // Transparent outer
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(64, 64, 45, 0, Math.PI * 2);
ctx.fill();
// Portal runes
ctx.strokeStyle = '#FFFFFF';
ctx.lineWidth = 2;
// Draw an X in the center
ctx.beginPath();
ctx.moveTo(44, 44);
ctx.lineTo(84, 84);
ctx.moveTo(84, 44);
ctx.lineTo(44, 84);
ctx.stroke();
// Convert the canvas to an image
const img = new Image();
img.src = canvas.toDataURL();
// Store in asset loader
assetLoader.assets[this.portalId] = img;
console.log('PortalEntity: Fallback image created and stored');
}
/**
* Update the portal entity
* @param {number} deltaTime - Time since last update in ms
* @param {Entity} player - Player entity for proximity detection
*/
update(deltaTime, player) {
if (this.isStatic) {
// No need to update position/velocity for static objects
}
// Update animation time
this.animationTime += deltaTime * 0.001; // Convert to seconds
// Check if player is nearby for interaction
this.updatePlayerProximity(player);
// Update glow effect
this.updateGlowEffect(deltaTime);
// Check for interaction (Enter key press)
this.checkForInteraction();
// Debug logging every 60 frames
if (Math.round(this.animationTime * 10) % 60 === 0) {
console.log(`Portal update: animTime=${this.animationTime.toFixed(2)}, glow=${this.glowIntensity.toFixed(2)}, isNearby=${this.isPlayerNearby}`);
}
}
/**
* Update player proximity status
* @param {Entity} player - Player entity
*/
updatePlayerProximity(player) {
if (player) {
const dx = player.x - this.x;
const dy = player.y - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
// Track previous state for transition logging
const wasNearby = this.isPlayerNearby;
// Update proximity state
this.isPlayerNearby = distance <= this.interactionDistance;
// Log state changes
if (!wasNearby && this.isPlayerNearby) {
console.log(`PortalEntity: Player entered interaction range (${distance.toFixed(2)} units)`);
// Play vortex/whoosh sound when player enters range
this.playProximitySound();
} else if (wasNearby && !this.isPlayerNearby) {
console.log(`PortalEntity: Player left interaction range (${distance.toFixed(2)} units)`);
}
// Handle interaction prompt fade
if (this.isPlayerNearby) {
// Fade in prompt
this.interactionPromptAlpha = Math.min(1, this.interactionPromptAlpha + 0.05);
this.showPrompt = true;
} else {
// Fade out prompt
this.interactionPromptAlpha = Math.max(0, this.interactionPromptAlpha - 0.05);
if (this.interactionPromptAlpha <= 0) {
this.showPrompt = false;
}
}
} else {
// No player reference, assume not nearby
this.isPlayerNearby = false;
this.showPrompt = false;
this.interactionPromptAlpha = 0;
}
}
/**
* Update glow intensity based on animation time and player proximity
* @param {number} deltaTime - Time elapsed since last update
*/
updateGlowEffect(deltaTime) {
// The TV and Jukebox don't use deltaTime for their glow animation
// This ensures consistent animation speed regardless of frame rate
this.glowIntensity += this.glowDirection * this.glowSpeed;
// Reverse direction when reaching min/max values
if (this.glowIntensity > this.maxGlowIntensity) {
this.glowIntensity = this.maxGlowIntensity;
this.glowDirection = -1;
} else if (this.glowIntensity < this.minGlowIntensity) {
this.glowIntensity = this.minGlowIntensity;
this.glowDirection = 1;
}
// Enhance glow when player is nearby
this.proximityBoost = this.isPlayerNearby ? 1.5 : 1.0;
// Debug logging occasionally
if (Math.random() < 0.01) {
console.log(`Portal glow: intensity=${this.glowIntensity.toFixed(2)}, direction=${this.glowDirection}, proximityBoost=${this.proximityBoost}`);
}
}
/**
* Check for user interaction with the portal
*/
checkForInteraction() {
// Only check for interaction if player is nearby and interaction is enabled
if (this.isPlayerNearby && this.interactionEnabled) {
// Use the enhanced input system with all possible Enter key detection methods
const isEnterPressed = input.enterKeyPressed ||
input.numpadEnterPressed ||
input.keys['Enter'] ||
input.keys['NumpadEnter'] ||
input.isKeyPressed('Enter') ||
input.isKeyPressed('NumpadEnter');
// Specific Enter key press detection (not just held down)
const isNewEnterPress = isEnterPressed && !this.wasEnterPressed;
// Aggressive logging to debug the issue
console.log(`Portal interaction check:`, {
isPlayerNearby: this.isPlayerNearby,
isEnterPressed: isEnterPressed,
wasEnterPressed: this.wasEnterPressed,
isNewEnterPress: isNewEnterPress,
enterFlag: input.enterKeyPressed,
numpadEnterFlag: input.numpadEnterPressed,
enterKey: input.keys['Enter'],
numpadEnterKey: input.keys['NumpadEnter'],
time: new Date().toISOString(),
position: `(${this.x.toFixed(2)}, ${this.y.toFixed(2)})`
});
// Only detect a new press (not holding)
if (isNewEnterPress) {
console.log('PortalEntity: NEW Enter key press detected, navigating to URL!');
// Force this to run async to avoid any race conditions
setTimeout(() => this.interact(), 50);
}
// Update previous state
this.wasEnterPressed = isEnterPressed;
}
}
/**
* Handle portal interaction (navigate to URL)
*/
interact() {
if (!this.interactionEnabled) return;
console.log(`PortalEntity: Navigating to ${this.targetUrl}`);
// Create a transition effect before opening URL
this.createTransitionEffect();
// Open URL in a new tab
window.open(this.targetUrl, '_blank');
}
/**
* Create a visual transition effect when interacting with the portal
*/
createTransitionEffect() {
// Create and style the overlay
const overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = this.glowColor;
overlay.style.opacity = '0';
overlay.style.pointerEvents = 'none';
overlay.style.zIndex = '1000';
// Add to body
document.body.appendChild(overlay);
// Animate the transition
setTimeout(() => {
overlay.style.opacity = '0.5';
overlay.style.transition = 'opacity 0.2s ease-in-out';
setTimeout(() => {
overlay.style.opacity = '0';
overlay.style.transition = 'opacity 0.3s ease-in-out';
setTimeout(() => {
document.body.removeChild(overlay);
}, 300);
}, 200);
}, 50);
}
/**
* Draw the portal entity
* @param {CanvasRenderingContext2D} ctx - Canvas rendering context
* @param {number} screenX - Screen X position to draw at
* @param {number} screenY - Screen Y position to draw at
* @param {number} width - Width to draw
* @param {number} height - Height to draw
* @param {number} zOffset - Z-axis offset
*/
draw(ctx, screenX, screenY, width, height, zOffset) {
// Calculate adjusted position with proper grounding
const groundingFactor = 1.8; // Adjust to make portal appear at right height
const adjustedScreenY = screenY - height * (1 - groundingFactor);
// Apply vertical offset based on z position
const drawY = adjustedScreenY - (this.z * 2);
// Debug log drawing occasionally
if (Math.random() < 0.005) {
console.log(`Portal draw: screenX=${screenX}, screenY=${screenY}, glow=${this.glowIntensity.toFixed(2)}`);
console.log(`Portal image loaded: ${!!assetLoader.assets[this.portalId]}`);
}
// Save the current context state
ctx.save();
// Check if portal image is loaded
if (assetLoader.assets[this.portalId]) {
// Calculate scale factor to fit in the desired width/height
const img = assetLoader.assets[this.portalId];
const scale = Math.min(width * 14 / img.width, height * 14 / img.height);
// Calculate centered position
const drawWidth = img.width * scale;
const drawHeight = img.height * scale;
const drawX = screenX - drawWidth / 2;
// Apply glow effect with shadow
if (this.glowIntensity > 0.1) {
// Set glow color
ctx.shadowColor = this.glowColor;
// Apply proximity boost to make glow more intense when player is nearby
const boostFactor = this.proximityBoost || 1.0;
ctx.shadowBlur = (15 + (this.glowIntensity * 15)) * boostFactor;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
}
// Draw the portal image WITH the shadow effect applied
ctx.drawImage(img, drawX, drawY - drawHeight, drawWidth, drawHeight);
} else {
// Fallback rendering if image isn't loaded
ctx.fillStyle = '#8A2BE2'; // BlueViolet
// Draw a portal-like shape
const portalWidth = width * 0.8;
const portalHeight = height * 1.5;
const portalX = screenX - portalWidth / 2;
const portalY = drawY - portalHeight;
// Apply glow to the fallback portal
if (this.glowIntensity > 0.1) {
ctx.shadowColor = this.glowColor;
// Apply same proximity boost as with the image
const boostFactor = this.proximityBoost || 1.0;
ctx.shadowBlur = (15 + (this.glowIntensity * 15)) * boostFactor;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
}
// Draw portal base shape
ctx.beginPath();
ctx.arc(screenX, drawY - portalHeight / 2, portalWidth / 2, 0, Math.PI * 2);
ctx.fill();
// Draw portal "X" in white
ctx.strokeStyle = 'white';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(screenX - 15, drawY - portalHeight / 2 - 15);
ctx.lineTo(screenX + 15, drawY - portalHeight / 2 + 15);
ctx.moveTo(screenX + 15, drawY - portalHeight / 2 - 15);
ctx.lineTo(screenX - 15, drawY - portalHeight / 2 + 15);
ctx.stroke();
}
// Draw interaction prompt if player is nearby
if (this.interactionPromptAlpha > 0) {
this.drawInteractionPrompt(ctx, screenX, drawY - height * -1);
}
// Restore context state
ctx.restore();
// Draw debug visuals if enabled
if (window.DEBUG_CONFIG && window.DEBUG_CONFIG.showEntityInfo) {
this.drawDebugInfo(ctx, screenX, adjustedScreenY);
}
}
/**
* Draw interaction prompt above the portal
* @param {CanvasRenderingContext2D} ctx - Canvas context
* @param {number} x - X position for the prompt
* @param {number} y - Y position for the prompt
*/
drawInteractionPrompt(ctx, x, y) {
ctx.save();
// Create dimensions for prompt window
const padding = 48;
const text = 'Visit AI Alchemist on X';
const textWidth = ctx.measureText(text).width;
const promptWidth = textWidth + (padding * 2);
const promptHeight = 60;
const promptX = x - promptWidth/2;
const promptY = y - 30;
// Create gradient background instead of solid color
const gradient = ctx.createLinearGradient(
promptX,
promptY,
promptX,
promptY + promptHeight
);
gradient.addColorStop(0, `rgba(40, 10, 60, ${this.interactionPromptAlpha * 0.9})`);
gradient.addColorStop(0.5, `rgba(80, 20, 120, ${this.interactionPromptAlpha * 0.9})`);
gradient.addColorStop(1, `rgba(40, 10, 60, ${this.interactionPromptAlpha * 0.9})`);
// Draw background with gradient
ctx.fillStyle = gradient;
ctx.fillRect(promptX, promptY, promptWidth, promptHeight);
// Draw border with glow effect
ctx.shadowColor = this.glowColor;
ctx.shadowBlur = 8 * this.glowIntensity;
ctx.strokeStyle = `rgba(138, 43, 226, ${this.interactionPromptAlpha})`;
ctx.lineWidth = 2;
ctx.strokeRect(promptX, promptY, promptWidth, promptHeight);
ctx.shadowBlur = 0;
// Draw text
ctx.fillStyle = `rgba(255, 255, 255, ${this.interactionPromptAlpha})`;
ctx.font = 'bold 18px monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, x, y - 10);
// Draw key indicator
ctx.font = 'bold 16px monospace';
ctx.fillStyle = `rgba(138, 43, 226, ${this.interactionPromptAlpha})`;
ctx.fillText('[ ENTER ]', x, y + 15);
ctx.restore();
}
/**
* Play a lower-pitched vortex/whoosh sound when player approaches the portal
*/
playProximitySound() {
try {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// Create noise buffer for the whoosh base - longer for lower pitch feel
const bufferSize = audioCtx.sampleRate * 1.8; // 1.8 seconds of sound (longer than original 1.5)
const noiseBuffer = audioCtx.createBuffer(2, bufferSize, audioCtx.sampleRate);
// Fill buffer with noise
const leftChannel = noiseBuffer.getChannelData(0);
const rightChannel = noiseBuffer.getChannelData(1);
// Create noise with a specific envelope for whoosh effect
for(let i = 0; i < bufferSize; i++) {
// Position as a normalized value (0 to 1)
const position = i / bufferSize;
// Envelope shape - start low, build up, then fade
// This creates the classic 'whoosh' shape
let envelope;
if (position < 0.2) {
// Initial build up
envelope = position * 5 * 0.2; // Ramp up to 0.2
} else if (position < 0.4) {
// Continue rising
envelope = 0.2 + (position - 0.2) * 5 * 0.6; // Ramp up to 0.8
} else if (position < 0.7) {
// Peak and begin descent
envelope = 0.8 - (position - 0.4) * (0.8 / 0.3) * 0.5; // Drop to 0.4
} else {
// Tail off
envelope = 0.4 * (1 - (position - 0.7) / 0.3);
}
// Add some variation between channels
leftChannel[i] = (Math.random() * 2 - 1) * envelope;
rightChannel[i] = (Math.random() * 2 - 1) * envelope;
}
// Create noise source node
const noiseSource = audioCtx.createBufferSource();
noiseSource.buffer = noiseBuffer;
// Create a bandpass filter for the 'whoosh' sound - LOWER frequencies for return portal
const bandpass = audioCtx.createBiquadFilter();
bandpass.type = 'bandpass';
bandpass.frequency.setValueAtTime(60, audioCtx.currentTime); // Lower starting frequency (60 vs 100)
bandpass.frequency.exponentialRampToValueAtTime(1200, audioCtx.currentTime + 0.8); // Lower peak (1200 vs 2000) and slower sweep
bandpass.frequency.exponentialRampToValueAtTime(300, audioCtx.currentTime + 1.8); // Lower ending (300 vs 500)
bandpass.Q.value = 1.3; // Wider bandwidth for more rumble
// Create a lowpass filter to emphasize deeper tones instead of a highpass
const lowpass = audioCtx.createBiquadFilter();
lowpass.type = 'lowpass';
lowpass.frequency.value = 800; // Only allow lower frequencies through
// Create an LFO for wobble effect - slower for lower pitch feel
const lfo = audioCtx.createOscillator();
lfo.type = 'sine';
lfo.frequency.value = 0.5; // Slower modulation (0.5 vs 0.8)
const lfoGain = audioCtx.createGain();
lfoGain.gain.value = 120; // Stronger modulation for heavier effect
// Create master gain node for overall volume - slower attack/release for lower pitch
const masterGain = audioCtx.createGain();
masterGain.gain.setValueAtTime(0.05, audioCtx.currentTime); // Start quieter
masterGain.gain.linearRampToValueAtTime(0.35, audioCtx.currentTime + 0.6); // Slower ramp up, louder peak
masterGain.gain.linearRampToValueAtTime(0.1, audioCtx.currentTime + 1.8); // Slower fade out
// Add reverb/echo effect - longer for lower pitch
const convolver = audioCtx.createConvolver();
const reverbLength = audioCtx.sampleRate * 1.5; // Longer reverb (1.5 vs 1.0)
const reverbBuffer = audioCtx.createBuffer(2, reverbLength, audioCtx.sampleRate);
const reverbLeftChannel = reverbBuffer.getChannelData(0);
const reverbRightChannel = reverbBuffer.getChannelData(1);
// Create reverb impulse - slower decay for lower pitch
for(let i = 0; i < reverbLength; i++) {
const decay = Math.exp(-i / (audioCtx.sampleRate * 0.5)); // Slower decay (0.5 vs 0.3)
// Add subtle low frequency oscillation to reverb
const lfo = Math.sin(i / (audioCtx.sampleRate * 0.3)) * 0.1;
reverbLeftChannel[i] = ((Math.random() * 2 - 1) + lfo) * decay;
reverbRightChannel[i] = ((Math.random() * 2 - 1) - lfo) * decay;
}
convolver.buffer = reverbBuffer;
// Connect LFO to bandpass frequency
lfo.connect(lfoGain);
lfoGain.connect(bandpass.frequency);
// Connect main audio path
noiseSource.connect(bandpass);
bandpass.connect(lowpass); // Using lowpass instead of highpass for lower tone
lowpass.connect(convolver);
convolver.connect(masterGain);
lowpass.connect(masterGain); // Parallel dry signal
masterGain.connect(audioCtx.destination);
// Start sound
noiseSource.start();
lfo.start();
// Add a deeper tonal element for the 'vortex' quality - lower pitched
const toneOsc = audioCtx.createOscillator();
toneOsc.type = 'sine';
toneOsc.frequency.setValueAtTime(300, audioCtx.currentTime); // Lower starting (300 vs 600)
toneOsc.frequency.exponentialRampToValueAtTime(80, audioCtx.currentTime + 1.8); // Lower ending (80 vs 150)
const toneGain = audioCtx.createGain();
toneGain.gain.setValueAtTime(0, audioCtx.currentTime);
toneGain.gain.linearRampToValueAtTime(0.15, audioCtx.currentTime + 0.4); // Slower attack, stronger presence
toneGain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 1.8);
toneOsc.connect(toneGain);
toneGain.connect(masterGain);
toneOsc.start();
toneOsc.stop(audioCtx.currentTime + 1.8);
// Add a low rumble oscillator for the return portal
const rumbleOsc = audioCtx.createOscillator();
rumbleOsc.type = 'triangle';
rumbleOsc.frequency.setValueAtTime(50, audioCtx.currentTime);
rumbleOsc.frequency.exponentialRampToValueAtTime(120, audioCtx.currentTime + 0.8);
rumbleOsc.frequency.exponentialRampToValueAtTime(40, audioCtx.currentTime + 1.8);
const rumbleGain = audioCtx.createGain();
rumbleGain.gain.setValueAtTime(0, audioCtx.currentTime);
rumbleGain.gain.linearRampToValueAtTime(0.08, audioCtx.currentTime + 0.5); // Subtle but noticeable
rumbleGain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 1.8);
rumbleOsc.connect(rumbleGain);
rumbleGain.connect(masterGain);
rumbleOsc.start();
rumbleOsc.stop(audioCtx.currentTime + 1.8);
// Schedule cleanup - longer for lower-pitched sound
setTimeout(() => {
try {
lfo.stop();
noiseSource.stop();
audioCtx.close();
} catch (err) {
console.warn('Error cleaning up portal sound:', err);
}
}, 1800); // 1.8 seconds instead of 1.5
debug('PortalEntity: Played lower-pitched vortex/whoosh proximity sound');
} catch (err) {
console.error(`PortalEntity: Error playing proximity sound: ${err.message}`);
}
}
/**
* Draw debug information for the portal
* @param {CanvasRenderingContext2D} ctx - Canvas context
* @param {number} x - X position for debug info
* @param {number} y - Y position for debug info
*/
drawDebugInfo(ctx, x, y) {
ctx.save();
// Draw collision box
ctx.strokeStyle = this.isPlayerNearby ? 'rgba(0, 255, 0, 0.5)' : 'rgba(255, 0, 0, 0.5)';
ctx.lineWidth = 2;
ctx.strokeRect(x - this.width / 2, y - this.height / 2, this.width, this.height);
// Draw interaction radius
ctx.strokeStyle = 'rgba(138, 43, 226, 0.3)';
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.arc(x, y, this.interactionDistance * 32, 0, Math.PI * 2);
ctx.stroke();
ctx.setLineDash([]);
// Draw entity info
ctx.fillStyle = 'white';
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(`Portal(${this.x.toFixed(1)},${this.y.toFixed(1)})`, x, y - this.height);
// Draw interaction status
ctx.fillStyle = this.isPlayerNearby ? 'rgba(0, 255, 0, 0.8)' : 'rgba(255, 0, 0, 0.8)';
ctx.fillText(this.isPlayerNearby ? 'IN RANGE' : 'OUT OF RANGE', x, y + this.height);
ctx.restore();
}
}