-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
737 lines (635 loc) · 33.4 KB
/
index.html
File metadata and controls
737 lines (635 loc) · 33.4 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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
<!DOCTYPE html>
<html lang="en">
<!-- https://github.com/KuJoe/Scruffy64 -->
<head>
<!-- HTML Meta Tags -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Scruffy64 - Interactive Avatar Head Demo</title>
<meta name="description" content="Scruffy64 - A demo of an interactive head of Scruffy from Futurama in the style of the Super Mario 64 title screen.">
<!-- Facebook Meta Tags -->
<meta property="og:url" content="https://scruffy64.kujoe.net/">
<meta property="og:type" content="website">
<meta property="og:title" content="Scruffy64 - Interactive Avatar Head">
<meta property="og:description" content="Scruffy64 - An interactive head of Scruffy from Futurama in the style of the Super Mario 64 title screen.">
<meta property="og:image" content="https://scruffy64.kujoe.net/super64.png">
<!-- Twitter Meta Tags -->
<meta name="twitter:card" content="summary_large_image">
<meta property="twitter:domain" content="scruffy64.kujoe.net">
<meta property="twitter:url" content="https://scruffy64.kujoe.net/">
<meta name="twitter:title" content="Scruffy64 - Interactive Avatar Head">
<meta name="twitter:description" content="Scruffy64 - An interactive head of Scruffy from Futurama in the style of the Super Mario 64 title screen.">
<meta name="twitter:image" content="https://scruffy64.kujoe.net/super64.png">
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.165.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.165.0/examples/jsm/"
}
}
</script>
<style>
body {
margin: 0;
overflow: hidden; /* Hide scrollbars */
display: flex;
flex-direction: column; /* Arrange content vertically */
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #1a1a2e; /* Dark background */
font-family: 'Inter', sans-serif; /* Modern font */
color: #e0e0e0;
position: relative; /* For absolute positioning of UI elements */
touch-action: none; /* Prevent default touch actions like scrolling/zooming */
}
canvas {
display: block;
width: 100vw; /* Full viewport width */
height: 100vh; /* Full viewport height */
background-color: transparent; /* Scene background is handled by Three.js */
position: absolute; /* Position canvas behind UI */
top: 0;
left: 0;
z-index: 1;
}
#loading-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
display: flex;
justify-content: center;
align-items: center;
color: white;
font-size: 1.5em;
z-index: 1000;
border-radius: 10px; /* Rounded corners for overlay */
}
.spinner {
border: 4px solid rgba(255, 255, 255, 0.3);
border-top: 4px solid #fff;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin-right: 15px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Control Panel UI - Removed */
/* All .control-button, #randomActionButton, #resetButton styles are removed */
</style>
</head>
<body>
<div id="loading-overlay">
<div class="spinner"></div>
Loading Avatar...
</div>
<canvas id="avatarCanvas"></canvas>
<!-- Control Panel div and all its buttons are removed -->
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import TWEEN from 'three/addons/libs/tween.module.min.js';
// --- Global Variables ---
let scene, camera, renderer;
let avatarHead; // This will hold our loaded 3D model
let targetRotationX = 0;
let targetRotationY = 0;
const rotationSmoothness = 0.08; // How quickly the head rotates towards the target (0.0 to 1.0)
const maxPitch = Math.PI / 4; // Max up/down rotation (45 degrees)
const maxYaw = Math.PI / 3; // Max left/right rotation (60 degrees)
// Store initial avatar state for reset functionality
const initialAvatarPosition = new THREE.Vector3(0, 0, 0);
const initialAvatarScale = new THREE.Vector3(3.75, 3.75, 3.75);
const initialAvatarRotation = new THREE.Euler(0, 0, 0);
const loadingOverlay = document.getElementById('loading-overlay');
// References to control buttons are removed
// --- Mouse/Touch Control Management ---
let isDragging = false; // Flag for mouse/touch manipulation (pull, pinch, squish)
let dragStartPosition = { x: 0, y: 0 };
let initialModelPositionOnDrag = new THREE.Vector3();
let initialModelScaleOnDrag = new THREE.Vector3();
let mouseControlEnabled = true; // Flag for regular mouse/touch-based rotation
// activeButtonTweenCount and its usage related to buttons is removed
// --- Idle Movement Variables ---
let idleTargetPosition = new THREE.Vector3().copy(initialAvatarPosition);
let idleTargetRotation = new THREE.Euler().copy(initialAvatarRotation);
let lastIdleTargetChangeTime = 0;
const idleTargetChangeInterval = 3000; // Change idle target every 3 seconds
const idleMovementRangePosition = 2.0; // Increased for more noticeable positional idle movement
const idleMovementRangeRotation = Math.PI / 10; // Increased for more noticeable rotational idle movement
// --- Initialization Function ---
function init() {
// Scene setup
scene = new THREE.Scene();
scene.background = null; // Set scene background to null to allow custom background plane to show
// Camera setup
camera = new THREE.PerspectiveCamera(
75, // Field of view
window.innerWidth / window.innerHeight, // Aspect ratio
0.1, // Near clipping plane
1000 // Far clipping plane
);
camera.position.z = 7.5;
// Renderer setup
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById('avatarCanvas'),
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.shadowMap.enabled = true;
// Lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
directionalLight.position.set(2, 3, 2);
directionalLight.castShadow = true;
scene.add(directionalLight);
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
directionalLight.shadow.camera.near = 0.5;
directionalLight.shadow.camera.far = 50;
directionalLight.shadow.camera.left = -5;
directionalLight.shadow.camera.right = 5;
directionalLight.shadow.camera.top = 5;
directionalLight.shadow.camera.bottom = -5;
// --- Create 3D Background Plane with Image Texture ---
const textureLoader = new THREE.TextureLoader();
textureLoader.load(
"https://scruffy64.kujoe.net/super64.png", // The provided image URL
function(texture) {
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
// Adjust repeat based on the plane size and desired tile density
// A 64x64 texture on a 1000x1000 plane needs to repeat (1000/64) times
const repeatX = 1000 / 64;
const repeatY = 1000 / 64;
texture.repeat.set(repeatX, repeatY);
const backgroundMaterial = new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
opacity: 1.0 // Set opacity to 1.0
});
const backgroundGeometry = new THREE.PlaneGeometry(1000, 1000); // Large plane
const backgroundMesh = new THREE.Mesh(backgroundGeometry, backgroundMaterial);
backgroundMesh.position.z = -200; // Position far behind the avatar
scene.add(backgroundMesh);
},
undefined, // Progress callback
function(error) {
console.error('An error occurred loading the background texture:', error);
}
);
// --- Load 3D Model ---
const gltfLoader = new GLTFLoader();
gltfLoader.load(
'https://scruffy64.kujoe.net/scruffy.glb',
function (gltf) {
avatarHead = gltf.scene;
scene.add(avatarHead);
avatarHead.scale.copy(initialAvatarScale);
avatarHead.position.copy(initialAvatarPosition);
avatarHead.rotation.copy(initialAvatarRotation);
loadingOverlay.style.display = 'none'; // Hide loading overlay
// Set initial idle targets
setNewIdleTargets();
},
function (xhr) {
const percent = Math.round(xhr.loaded / xhr.total * 100);
loadingOverlay.textContent = `Loading Avatar... ${percent}%`;
},
function (error) {
console.error('An error occurred loading the GLTF model:', error);
loadingOverlay.textContent = 'Failed to load avatar. Check console for details.';
}
);
// --- Event Listeners ---
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('resize', onWindowResize);
// Mouse manipulation event listeners on the canvas
renderer.domElement.addEventListener('mousedown', onCanvasMouseDown);
window.addEventListener('mouseup', onWindowMouseUp); // Listen on window to catch release outside canvas
window.addEventListener('mousemove', onCanvasMouseMove); // Listen on window for continuous drag
// Touch manipulation event listeners on the canvas
renderer.domElement.addEventListener('touchstart', onCanvasTouchStart, { passive: false });
window.addEventListener('touchend', onWindowTouchEnd); // Listen on window to catch release outside canvas
window.addEventListener('touchmove', onCanvasTouchMove, { passive: false });
// Button event listeners are removed
animate();
}
// --- Event Handlers (for Regular Mouse/Touch Rotation) ---
function onMouseMove(event) {
// Only apply this rotation if not currently dragging for manipulation AND mouse control is enabled
if (!isDragging && mouseControlEnabled) {
const mouseX = (event.clientX / window.innerWidth) * 2 - 1;
const mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
targetRotationY = -mouseX * maxYaw;
targetRotationX = -mouseY * maxPitch;
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// --- Mouse Manipulation Event Handlers ---
function onCanvasMouseDown(event) {
if (!avatarHead) return;
// Stop any ongoing tweens and disable regular controls
TWEEN.removeAll();
mouseControlEnabled = false;
isDragging = true;
// activeButtonTweenCount and its usage related to buttons is removed
dragStartPosition.x = event.clientX;
dragStartPosition.y = event.clientY;
initialModelPositionOnDrag.copy(avatarHead.position);
initialModelScaleOnDrag.copy(avatarHead.scale);
event.preventDefault();
}
function onCanvasMouseMove(event) {
if (!isDragging || !avatarHead) return;
const deltaX = event.clientX - dragStartPosition.x;
const deltaY = event.clientY - dragStartPosition.y;
const sensitivity = 0.005 * (initialAvatarScale.x / 3.75); // Adjust sensitivity based on model scale
const scaleSensitivity = 0.002 * (initialAvatarScale.x / 3.75);
if (event.shiftKey) { // Squish/Stretch
const scaleX = initialModelScaleOnDrag.x + deltaX * scaleSensitivity;
const scaleY = initialModelScaleOnDrag.y - deltaY * scaleSensitivity;
const scaleZ = initialModelScaleOnDrag.z * (1 / ((scaleX / initialModelScaleOnDrag.x + scaleY / initialModelScaleOnDrag.y) / 2));
avatarHead.scale.set(scaleX, scaleY, scaleZ);
} else if (event.ctrlKey || event.metaKey) { // Pinch/Zoom (uniform scale)
const scaleFactor = 1 + (deltaX - deltaY) * scaleSensitivity;
avatarHead.scale.copy(initialModelScaleOnDrag).multiplyScalar(scaleFactor);
} else { // Pull/Translate
avatarHead.position.x = initialModelPositionOnDrag.x + deltaX * sensitivity;
avatarHead.position.y = initialModelPositionOnDrag.y - deltaY * sensitivity;
// Also update target rotations for mouse control so it doesn't jump when re-enabled
targetRotationX = avatarHead.rotation.x;
targetRotationY = avatarHead.rotation.y;
}
event.preventDefault(); // Prevent text selection etc.
}
function onWindowMouseUp(event) {
if (!isDragging) return;
isDragging = false;
// Animate back to initial position and scale
new TWEEN.Tween(avatarHead.position)
.to(initialAvatarPosition, 700)
.easing(TWEEN.Easing.Elastic.Out)
.onComplete(() => {
mouseControlEnabled = true; // Re-enable regular rotation AND idle movement
// Ensure rotation targets match current head rotation to avoid jump
targetRotationX = avatarHead.rotation.x;
targetRotationY = avatarHead.rotation.y;
setNewIdleTargets(); // Reset idle movement targets for a fresh start
})
.start();
new TWEEN.Tween(avatarHead.scale)
.to(initialAvatarScale, 700)
.easing(TWEEN.Easing.Elastic.Out)
.start();
}
// --- Touch Manipulation Event Handlers (Mirroring Mouse Logic) ---
function onCanvasTouchStart(event) {
if (!avatarHead) return;
if (event.touches.length === 1) { // Single touch for pull/rotation
// Use the first touch point
event.clientX = event.touches[0].clientX;
event.clientY = event.touches[0].clientY;
onCanvasMouseDown(event); // Re-use mouse down logic
} else if (event.touches.length === 2) { // Two touches for pinch/squish/stretch
// Handle multi-touch for scaling
TWEEN.removeAll();
mouseControlEnabled = false;
isDragging = true; // Use isDragging for touch scale too
// activeButtonTweenCount and its usage related to buttons is removed
// Store initial positions for calculating distance/angle for pinch/squish/stretch
dragStartPosition.x = (event.touches[0].clientX + event.touches[1].clientX) / 2;
dragStartPosition.y = (event.touches[0].clientY + event.touches[1].clientY) / 2;
initialModelPositionOnDrag.copy(avatarHead.position);
initialModelScaleOnDrag.copy(avatarHead.scale);
// Store initial touch distance for pinch/zoom
currentTouchDistance = getTouchDistance(event.touches);
currentTouchAngle = getTouchAngle(event.touches);
event.preventDefault(); // Prevent scrolling/zooming
}
}
let currentTouchDistance = 0;
let currentTouchAngle = 0; // For squish/stretch via touch rotation
function onCanvasTouchMove(event) {
if (!isDragging || !avatarHead) return; // isDragging ensures we are in a manipulation mode
if (event.touches.length === 1) { // Single touch for pull/rotate
event.clientX = event.touches[0].clientX;
event.clientY = event.touches[0].clientY;
// Re-use mouse move logic for pull (translation)
// Note: Shift/Ctrl key are not available on touch.
// For touch, we'll assume single touch is pull/translate.
const deltaX = event.clientX - dragStartPosition.x;
const deltaY = event.clientY - dragStartPosition.y;
const sensitivity = 0.005 * (initialAvatarScale.x / 3.75);
avatarHead.position.x = initialModelPositionOnDrag.x + deltaX * sensitivity;
avatarHead.position.y = initialModelPositionOnDrag.y - deltaY * sensitivity;
targetRotationX = avatarHead.rotation.x;
targetRotationY = avatarHead.rotation.y;
} else if (event.touches.length === 2) { // Two touches for pinch/squish/stretch
const newTouchDistance = getTouchDistance(event.touches);
const newTouchAngle = getTouchAngle(event.touches);
const pinchDelta = newTouchDistance - currentTouchDistance;
// const twistDelta = newTouchAngle - currentTouchAngle; // Could use this for Z-rotation
const scaleSensitivity = 0.005 * (initialAvatarScale.x / 3.75); // Adjusted for touch
// const rotationSensitivity = 0.01; // For twist
// Pinch/Zoom (uniform scale) based on distance change
const scaleFactor = 1 + pinchDelta * scaleSensitivity;
avatarHead.scale.copy(initialModelScaleOnDrag).multiplyScalar(scaleFactor);
// Simple squish/stretch could be based on horizontal/vertical touch spread if more complex gestures are desired
// For now, let's keep it simple with uniform scale via pinch.
// Update current touch metrics for next frame
currentTouchDistance = newTouchDistance;
currentTouchAngle = newTouchAngle;
}
event.preventDefault(); // Prevent scrolling/zooming
}
function onWindowTouchEnd(event) {
// Check if all touches are gone, or if only one touch remains after two-finger gesture
if (event.touches.length === 0 && isDragging) {
isDragging = false;
// Re-use mouse up logic for spring back
new TWEEN.Tween(avatarHead.position)
.to(initialAvatarPosition, 700)
.easing(TWEEN.Easing.Elastic.Out)
.onComplete(() => {
mouseControlEnabled = true;
targetRotationX = avatarHead.rotation.x;
targetRotationY = avatarHead.rotation.y;
setNewIdleTargets();
})
.start();
new TWEEN.Tween(avatarHead.scale)
.to(initialAvatarScale, 700)
.easing(TWEEN.Easing.Elastic.Out)
.start();
} else if (event.touches.length === 1 && isDragging) {
// If a two-finger gesture ends but one finger is still down,
// we might transition to single-finger drag (pull/rotate)
// Reset drag start for single finger
dragStartPosition.x = event.touches[0].clientX;
dragStartPosition.y = event.touches[0].clientY;
initialModelPositionOnDrag.copy(avatarHead.position);
initialModelScaleOnDrag.copy(avatarHead.scale); // Reset scale for the start of new drag
currentTouchDistance = 0; // Reset multi-touch specific variables
currentTouchAngle = 0;
}
}
// Helper function to get distance between two touches
function getTouchDistance(touches) {
const dx = touches[0].clientX - touches[1].clientX;
const dy = touches[0].clientY - touches[1].clientY;
return Math.sqrt(dx * dx + dy * dy);
}
// Helper function to get angle between two touches (for potential twist/squish-stretch via rotation)
function getTouchAngle(touches) {
const dx = touches[0].clientX - touches[1].clientX;
const dy = touches[0].clientY - touches[1].clientY;
return Math.atan2(dy, dx);
}
// --- Avatar Animation Functions (used by idle or if a random action button were present) ---
// These functions are now only called internally by idle movement
// or if you re-add a 'Random Action!' button.
function triggerAvatarAnimation(type) {
if (!avatarHead) return;
// Stop any direct mouse/touch manipulation and disable regular controls AND idle movement
TWEEN.removeAll();
mouseControlEnabled = false;
isDragging = false;
// activeButtonTweenCount and its usage related to buttons is removed
const animationDuration = 250;
const resetDuration = 600;
const pullAmount = 6.0;
const pullRotation = Math.PI / 18;
const currentPos = new THREE.Vector3().copy(avatarHead.position);
const currentRot = new THREE.Euler().copy(avatarHead.rotation);
const currentScale = new THREE.Vector3().copy(avatarHead.scale);
let targetPos = new THREE.Vector3().copy(currentPos);
let targetRot = new THREE.Euler().copy(currentRot);
let targetScale = new THREE.Vector3().copy(currentScale);
let tweensToRun = [];
let shouldTweenPosition = false;
let shouldTweenRotation = false;
let shouldTweenScale = false;
switch (type) {
case 'pullLeft':
targetPos.x -= pullAmount;
targetRot.y -= pullRotation;
shouldTweenPosition = true;
shouldTweenRotation = true;
break;
case 'pullRight':
targetPos.x += pullAmount;
targetRot.y += pullRotation;
shouldTweenPosition = true;
shouldTweenRotation = true;
break;
case 'pullUp':
targetPos.y += pullAmount;
targetRot.x += pullRotation;
shouldTweenPosition = true;
shouldTweenRotation = true;
break;
case 'pullDown':
targetPos.y -= pullAmount;
targetRot.x -= pullRotation;
shouldTweenPosition = true;
shouldTweenRotation = true;
break;
case 'squish':
targetScale.x = initialAvatarScale.x * 1.1;
targetScale.y = initialAvatarScale.y * 0.9;
targetScale.z = initialAvatarScale.z * 1.1;
targetPos.y = initialAvatarPosition.y - (pullAmount * 0.2);
shouldTweenScale = true;
shouldTweenPosition = true;
break;
case 'stretch':
targetScale.x = initialAvatarScale.x * 0.9;
targetScale.y = initialAvatarScale.y * 1.1;
targetScale.z = initialAvatarScale.z * 0.9;
targetPos.y = initialAvatarPosition.y + (pullAmount * 0.2);
shouldTweenScale = true;
shouldTweenPosition = true;
break;
case 'randomWobble':
targetRot.x = currentRot.x + (Math.random() - 0.5) * Math.PI / 1.5;
targetRot.y = currentRot.y + (Math.random() - 0.5) * Math.PI / 1.5;
targetRot.z = currentRot.z + (Math.random() - 0.5) * Math.PI / 3;
shouldTweenRotation = true;
break;
case 'randomZoom':
shouldTweenScale = true;
const zoomFactor = 0.2 + Math.random() * 1.8; // Range: 0.2 to 2.0
targetScale.x = initialAvatarScale.x * zoomFactor;
targetScale.y = initialAvatarScale.y * zoomFactor;
targetScale.z = initialAvatarScale.z * zoomFactor;
break;
case 'randomTwist':
targetRot.z = currentRot.z + (Math.random() - 0.5) * Math.PI * 4;
shouldTweenRotation = true;
break;
default:
console.warn(`Unknown animation type: ${type}`);
return;
}
if (shouldTweenPosition) {
const posTween = new TWEEN.Tween(avatarHead.position)
.to(targetPos, animationDuration)
.easing(TWEEN.Easing.Quadratic.Out)
.chain(
new TWEEN.Tween(avatarHead.position)
.to(initialAvatarPosition, resetDuration) // Always return to initial position
.easing(TWEEN.Easing.Elastic.Out)
);
tweensToRun.push(posTween);
}
if (shouldTweenRotation) {
const rotTween = new TWEEN.Tween(avatarHead.rotation)
.to(targetRot, animationDuration)
.easing(TWEEN.Easing.Quadratic.Out)
.chain(
new TWEEN.Tween(avatarHead.rotation)
.to(initialAvatarRotation, resetDuration) // Always return to initial rotation
.easing(TWEEN.Easing.Elastic.Out)
);
tweensToRun.push(rotTween);
}
if (shouldTweenScale) {
const scaleTween = new TWEEN.Tween(avatarHead.scale)
.to(targetScale, animationDuration)
.easing(TWEEN.Easing.Quadratic.Out)
.chain(
new TWEEN.Tween(avatarHead.scale)
.to(initialAvatarScale, resetDuration * 1.5)
.easing(TWEEN.Easing.Elastic.Out)
);
tweensToRun.push(scaleTween);
}
if (tweensToRun.length > 0) {
// activeButtonTweenCount and its usage related to buttons is removed
// Re-enable mouse control directly after the tweens complete.
// This logic is now simpler as buttons are removed.
const lastTween = tweensToRun[tweensToRun.length - 1]; // Get the last tween in the chain
if (lastTween && lastTween.onCompleteCallback) { // Check if it's a valid tween with a callback
const originalOnComplete = lastTween.onCompleteCallback;
lastTween.onComplete(() => {
originalOnComplete(); // Call original if exists
mouseControlEnabled = true;
targetRotationX = avatarHead.rotation.x;
targetRotationY = avatarHead.rotation.y;
setNewIdleTargets();
});
} else if (tweensToRun.length === 1) { // If only one tween and no explicit chain
tweensToRun[0].onComplete(() => {
mouseControlEnabled = true;
targetRotationX = avatarHead.rotation.x;
targetRotationY = avatarHead.rotation.y;
setNewIdleTargets();
});
} else { // Fallback for cases where tween chaining might be complex or unexpected
// Set a timeout to re-enable mouse control
setTimeout(() => {
mouseControlEnabled = true;
targetRotationX = avatarHead.rotation.x;
targetRotationY = avatarHead.rotation.y;
setNewIdleTargets();
}, animationDuration + resetDuration + 100); // Wait for animations to finish
}
tweensToRun.forEach(tween => tween.start());
}
}
// resetView function is now standalone, no longer triggered by a button
function resetView() {
if (!avatarHead) return;
TWEEN.removeAll();
mouseControlEnabled = true;
isDragging = false;
// activeButtonTweenCount and its usage related to buttons is removed
targetRotationX = initialAvatarRotation.x;
targetRotationY = initialAvatarRotation.y;
new TWEEN.Tween(avatarHead.position)
.to(initialAvatarPosition, 700)
.easing(TWEEN.Easing.Elastic.Out)
.start();
new TWEEN.Tween(avatarHead.rotation)
.to(initialAvatarRotation, 700)
.easing(TWEEN.Easing.Elastic.Out)
.start();
new TWEEN.Tween(avatarHead.scale)
.to(initialAvatarScale, 700)
.easing(TWEEN.Easing.Elastic.Out)
.start();
setNewIdleTargets();
}
// --- Idle Movement Functions ---
function setNewIdleTargets() {
idleTargetPosition.set(
initialAvatarPosition.x + (Math.random() - 0.5) * idleMovementRangePosition,
initialAvatarPosition.y + (Math.random() - 0.5) * idleMovementRangePosition,
initialAvatarPosition.z + (Math.random() - 0.5) * idleMovementRangePosition
);
idleTargetRotation.set(
initialAvatarRotation.x + (Math.random() - 0.5) * idleMovementRangeRotation,
initialAvatarRotation.y + (Math.random() - 0.5) * idleMovementRangeRotation,
initialAvatarRotation.z + (Math.random() - 0.5) * idleMovementRangeRotation
);
lastIdleTargetChangeTime = performance.now();
}
// Random Action Selector - now only for internal use if you decide to re-add a "Random Action" trigger later
const randomActionTypes = [
'pullLeft', 'pullRight', 'pullUp', 'pullDown',
'squish', 'stretch',
'randomWobble',
'randomZoom',
'randomTwist'
];
// This function is no longer triggered by a button directly.
// It's kept here if you want to call it programmatically or re-add a button later.
function triggerRandomAction() {
const randomIndex = Math.floor(Math.random() * randomActionTypes.length);
const randomType = randomActionTypes[randomIndex];
console.log(`Triggering random action: ${randomType}`);
triggerAvatarAnimation(randomType);
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
TWEEN.update();
const currentTime = performance.now();
// Apply idle movement only if mouse control is enabled and not dragging
if (avatarHead && mouseControlEnabled && !isDragging) {
avatarHead.position.lerp(idleTargetPosition, 0.01);
avatarHead.rotation.x = THREE.MathUtils.lerp(avatarHead.rotation.x, idleTargetRotation.x, 0.01);
avatarHead.rotation.y = THREE.MathUtils.lerp(avatarHead.rotation.y, idleTargetRotation.y, 0.01);
avatarHead.rotation.z = THREE.MathUtils.lerp(avatarHead.rotation.z, idleTargetRotation.z, 0.01);
if (currentTime - lastIdleTargetChangeTime > idleTargetChangeInterval) {
setNewIdleTargets();
}
}
// Regular mouse-based rotation (still uses targetRotationX/Y)
// This happens even when idle movement is on, allowing mouse to override idle
if (avatarHead && mouseControlEnabled && !isDragging) {
avatarHead.rotation.x += (targetRotationX - avatarHead.rotation.x) * rotationSmoothness;
avatarHead.rotation.y += (targetRotationY - avatarHead.rotation.y) * rotationSmoothness;
}
renderer.render(scene, camera);
}
window.onload = init;
</script>
</body>
</html>