Repository navigation
Expand file tree
/
Copy pathkl_script_f.js
More file actions
2329 lines (2022 loc) · 86 KB
/
Copy pathkl_script_f.js
File metadata and controls
2329 lines (2022 loc) · 86 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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js';
let camera, scene, renderer;
let terrain, water;
const trees = [];
const clouds = [];
let waterVertices = [];
let hemiLight, dirLight, sun, glowSprite, moon, stars;
let audioListener, clickSound, natureSound, waterWalkSound, grassWalkSound, riverSound, nightRiverSound, riverAudioSource;
let audioStarted = false;
const birds = [];
// 플레이어 이동 및 시야 변수
let moveForward = false;
let moveBackward = false;
let moveLeft = false;
let moveRight = false;
let canJump = false;
// 커스텀 마우스 시야 제어 (드래그 방식)
let isDragging = false;
let yaw = 0;
let pitch = 0;
let prevTime = performance.now();
const velocity = new THREE.Vector3();
// 낚시 관련 변수
let isRodEquipped = true;
let castState = 'idle'; // 'idle', 'charging', 'flying', 'casted'
let castPower = 0;
let fishingRodGroup, bobber, fishingLine, bobberArrow;
let rod1Group, rod2Group, rod3Group, rodTipDummy;
let waterDropSound, struggleSound;
const bobberVelocity = new THREE.Vector3();
const bobberWorldPos = new THREE.Vector3();
const rodTipWorldPos = new THREE.Vector3();
let isMouseDown = false; // 마우스 클릭 상태 추적 (챔질용)
// 찌 흔들림 물리 (Spring)
const bobberSwingVel = new THREE.Vector3();
const bobberSwingOff = new THREE.Vector3();
const prevCameraPos = new THREE.Vector3();
// 물고기 및 낚시 로직 변수
let rodBendX = 0; // 좌우 휨 정도
let rodBendY = 0; // 상하 휨 정도
let biteTimer = 0;
let biteDuration = 0;
let fishSize = 0; // 물고기 난이도/힘 (1~10)
let fishDistance = 0; // 끌어올려야 하는 거리
let fishModel, fishMixer, fishAction, catchMsg;
let catchMsgTimeout = null;
let iceboxGroup = null;
let interactMsg = null;
let iceboxText = null;
let releaseMsg = null;
let storedFishCount = 0;
let hasFish = false;
// 물고기 종류 정의
const fishTypes = [
{ id: 'bamti', name: '밤티고기', asset: 'asset/bamti_fish.glb', minSize: 15, maxSize: 60, scaleMult: 0.8, storeScale: 0.1, caughtRot: [0, 0, Math.PI / 2], count: 0, model: null, mixer: null, action: null },
{ id: 'spiny', name: '가시납지리', asset: 'asset/Spiny_bitterling.glb', minSize: 5, maxSize: 15, scaleMult: 65.0, storeScale: 6.5, caughtRot: [-Math.PI / 2, 0, 0], count: 0, model: null, mixer: null, action: null },
{ id: 'hongnae', name: '홍지네가리', asset: 'asset/hongnae.glb', minSize: 8, maxSize: 20, scaleMult: 25.0, storeScale: 2.5, caughtRot: [-Math.PI / 2, 0, 0], count: 0, model: null, mixer: null, action: null }
];
let currentFishIndex = 0;
let rippleRings = []; // 입질 시 파동 효과
let struggleTimer = 0; // 실랑이 유지 시간
let mudParticles = []; // 도망갈 때 흙먼지 효과
init();
animate();
function getTerrainHeight(worldX, z) {
let y = 0;
const absZ = Math.abs(z);
// S자 강 형태를 위한 X좌표 오프셋 (지형 전체를 굽이치게 만듦)
const riverOffsetX = Math.sin(z * 0.006) * 180;
const x = worldX - riverOffsetX;
if (x < -60) {
y = 35 + Math.sin(x * 0.05) * 5 + Math.cos(z * 0.05) * 5;
} else if (x >= -60 && x < -40) {
const cliffTop = 25 + Math.sin(z * 0.03) * 10 + Math.cos(z * 0.07) * 8;
const t = (-x - 40) / 20;
y = -2 + Math.pow(t, 0.7) * (cliffTop + 2);
} else if (x >= -40 && x <= 70) {
y = -5;
} else if (x > 70 && x <= 110) {
const t = (x - 70) / 40;
y = -5 + t * 8; // x=110일때 y=3, 물 높이(1.0)와 정확히 맞물림
} else if (x > 110 && x <= 140) {
const t = (x - 110) / 30;
y = 3 + t * 1.0;
} else if (x > 140 && x <= 400) {
// 3가지 언덕 패턴을 Z 좌표 기준으로 번갈아 배치
const hillType = Math.floor(Math.abs(z / 180)) % 3;
if (hillType === 0) {
// 패턴 A: 완만하게 솟은 둥근 언덕
y = 4 + Math.sin((x - 130) * 0.038) * 6 + Math.cos(z * 0.025) * 3;
} else if (hillType === 1) {
// 패턴 B: 납작하고 물결치는 평지형
y = 4 + Math.sin(x * 0.04 + z * 0.02) * 2 + Math.cos(z * 0.05) * 1.5;
} else {
// 패턴 C: 비대칭으로 솟은 날카로운 언덕
y = 3 + Math.pow(Math.sin((x - 130) * 0.025), 2) * 18 + Math.sin(z * 0.03) * 2;
}
} else {
y = 6 + (x - 400) * 0.05;
}
if (absZ > 350) {
const overZ = absZ - 350;
y += Math.pow(overZ, 1.2) * 0.06 + Math.sin(x * 0.03) * 12 + Math.cos(z * 0.05) * 8;
}
return y;
}
function init() {
const container = document.getElementById('fishing-container');
// 1. Scene & Camera
scene = new THREE.Scene();
scene.background = new THREE.Color(0x87CEEB);
// 맵 크기 1400에 맞게 안개 밀도 조정
scene.fog = new THREE.FogExp2(0x87CEEB, 0.0016);
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 3000);
// 시작 지점: 물가(자갈밭) 근처 (x=110)
camera.position.set(110, 15, 0);
yaw = Math.PI / 2; // 강(왼쪽)을 바라봄
// --- Audio Setup ---
audioListener = new THREE.AudioListener();
camera.add(audioListener);
scene.add(camera); // 카메라에 붙은 낚시대를 렌더링하기 위해 씬에 추가
// 낚시대 재구성 (자연스럽고 사실적으로)
fishingRodGroup = new THREE.Group();
// 카본/대나무 느낌의 짙은 갈색 재질
const rodBodyMat = new THREE.MeshStandardMaterial({ color: 0x1a0a00, roughness: 0.7, metalness: 0.1 });
const rodGripMat = new THREE.MeshStandardMaterial({ color: 0x3b2a1a, roughness: 0.95 }); // 손잡이 코르크 느낌
const reelMat = new THREE.MeshStandardMaterial({ color: 0x888888, roughness: 0.3, metalness: 0.8 }); // 릴 은색
// 손잡이 (두꺼운 코르크 그립)
const gripGeo = new THREE.CylinderGeometry(0.07, 0.09, 1.5, 8);
const grip = new THREE.Mesh(gripGeo, rodGripMat);
grip.position.y = 0.75;
fishingRodGroup.add(grip);
// 로드 1단 (두꺼운 하단부)
rod1Group = new THREE.Group();
rod1Group.position.y = 1.5; // 손잡이 끝나는 지점
const rod1Geo = new THREE.CylinderGeometry(0.045, 0.07, 4.0, 8);
const rod1 = new THREE.Mesh(rod1Geo, rodBodyMat);
rod1.position.y = 2.0; // 실린더 중심 (길이 4.0의 절반)
rod1Group.add(rod1);
fishingRodGroup.add(rod1Group);
// 로드 2단 (중간)
rod2Group = new THREE.Group();
rod2Group.position.y = 4.0; // rod1 끝나는 지점 (로컬 y 4.0)
const rod2Geo = new THREE.CylinderGeometry(0.02, 0.045, 4.5, 8);
const rod2 = new THREE.Mesh(rod2Geo, rodBodyMat);
rod2.position.y = 2.25; // 실린더 중심
rod2Group.add(rod2);
rod1Group.add(rod2Group);
// 로드 3단 (가장 얇은 끝부분)
rod3Group = new THREE.Group();
rod3Group.position.y = 4.5; // rod2 끝나는 지점 (로컬 y 4.5)
const rod3Geo = new THREE.CylinderGeometry(0.005, 0.02, 4.0, 6);
const rod3 = new THREE.Mesh(rod3Geo, rodBodyMat);
rod3.position.y = 2.0; // 실린더 중심
rod3Group.add(rod3);
rod2Group.add(rod3Group);
// 낚시대 끝단 (줄이 연결되는 부분)
rodTipDummy = new THREE.Group();
rodTipDummy.position.y = 4.0; // rod3 끝
rod3Group.add(rodTipDummy);
// 릴 시트 (손잡이 위쪽 은색 릴)
const reelBodyGeo = new THREE.CylinderGeometry(0.12, 0.12, 0.3, 12);
const reelBody = new THREE.Mesh(reelBodyGeo, reelMat);
reelBody.position.set(-0.1, 1.7, 0);
reelBody.rotation.z = Math.PI / 2;
fishingRodGroup.add(reelBody);
// 릴 스풀
const reelSpoolGeo = new THREE.TorusGeometry(0.08, 0.03, 8, 16);
const reelSpool = new THREE.Mesh(reelSpoolGeo, reelMat);
reelSpool.position.set(-0.22, 1.7, 0);
reelSpool.rotation.y = Math.PI / 2;
fishingRodGroup.add(reelSpool);
// 줄 가이드 링 (3개, 각 마디의 끝부분에 배치하여 같이 휘어지게 함)
const guideMat = new THREE.MeshStandardMaterial({ color: 0xcccccc, roughness: 0.2, metalness: 0.9 });
const guide1 = new THREE.Mesh(new THREE.TorusGeometry(0.06, 0.008, 6, 12), guideMat);
guide1.position.set(0, 4.0, 0); // rod1Group의 끝
guide1.rotation.x = Math.PI / 2;
rod1Group.add(guide1);
const guide2 = new THREE.Mesh(new THREE.TorusGeometry(0.045, 0.008, 6, 12), guideMat);
guide2.position.set(0, 4.5, 0); // rod2Group의 끝
guide2.rotation.x = Math.PI / 2;
rod2Group.add(guide2);
const guide3 = new THREE.Mesh(new THREE.TorusGeometry(0.03, 0.008, 6, 12), guideMat);
guide3.position.set(0, 4.0, 0); // rod3Group의 끝 (초릿대)
guide3.rotation.x = Math.PI / 2;
rod3Group.add(guide3);
// 낚시대 그룹 위치: 카메라 오른쪽 하단, 앞으로 뻗음
// 손잡이가 화면 우하단에 오도록 위치 설정
fishingRodGroup.position.set(0.5, -1.8, -1.0);
// 앞으로 눕히고 약간 오른쪽으로 기울임
fishingRodGroup.rotation.order = 'YXZ';
fishingRodGroup.rotation.x = -Math.PI * 0.38; // 앞으로 약 68도 기울임
fishingRodGroup.rotation.z = Math.PI * 0.08; // 오른쪽으로 약간 기울임
camera.add(fishingRodGroup);
// 낚시대 끝단 로컬 위치 계산 (rod3 끝 = y: 9.5 → 월드 변환을 위해 Group 기준)
// rod tip은 fishingRodGroup 로컬 y=9.5에 위치
// animate에서 매 프레임 월드 좌표로 변환
// 찌 (Bobber) - 실제 낚시찌처럼 길쭉한 원통+구 형태
const bobberGroup = new THREE.Group();
const bobberTopGeo = new THREE.SphereGeometry(0.35, 12, 8, 0, Math.PI * 2, 0, Math.PI / 2);
const bobberTopMat = new THREE.MeshStandardMaterial({ color: 0xff2200, roughness: 0.3 });
const bobberTop = new THREE.Mesh(bobberTopGeo, bobberTopMat);
bobberTop.position.y = 0.2;
bobberGroup.add(bobberTop);
const bobberBotGeo = new THREE.SphereGeometry(0.35, 12, 8, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2);
const bobberBotMat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.3 });
const bobberBot = new THREE.Mesh(bobberBotGeo, bobberBotMat);
bobberBot.position.y = 0.2;
bobberGroup.add(bobberBot);
// 찌 안테나 (얇은 빨간 막대)
const antennaGeo = new THREE.CylinderGeometry(0.03, 0.015, 0.9, 6);
const antennaMat = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const antenna = new THREE.Mesh(antennaGeo, antennaMat);
antenna.position.y = 0.85;
bobberGroup.add(antenna);
bobber = bobberGroup;
bobber.visible = true;
scene.add(bobber);
// 물고기 모델 (GLB 에셋 다중 로드)
const gltfLoader = new GLTFLoader();
fishTypes.forEach((type) => {
const group = new THREE.Group();
scene.add(group);
group.visible = false;
type.model = group;
gltfLoader.load(type.asset, (gltf) => {
const model = gltf.scene;
// 물고기가 X축 방향으로 설정되어 있을 수 있으므로 필요한 경우 회전
model.rotation.y = Math.PI / 2;
group.add(model);
// 그림자 설정
model.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
// 애니메이션 믹서 설정
if (gltf.animations && gltf.animations.length > 0) {
type.mixer = new THREE.AnimationMixer(model);
type.action = type.mixer.clipAction(gltf.animations[0]);
}
});
});
// 초기 더미 참조
fishModel = fishTypes[0].model;
fishMixer = fishTypes[0].mixer;
fishAction = fishTypes[0].action;
// 입질 파동 이펙트 (Ripples)
for (let i = 0; i < 3; i++) {
const ringGeo = new THREE.RingGeometry(0.1, 0.2, 16);
const ringMat = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0, side: THREE.DoubleSide });
const ring = new THREE.Mesh(ringGeo, ringMat);
ring.rotation.x = -Math.PI / 2; // 수면과 평행
ring.visible = false;
scene.add(ring);
rippleRings.push({ mesh: ring, age: 0, active: false });
}
// 노란색 화살표 마커 (캐스팅 시 찌 위치 표시용)
const arrowGroup = new THREE.Group();
// 화살표 삼각형
const arrowShape = new THREE.Shape();
arrowShape.moveTo(0, 0);
arrowShape.lineTo(-0.3, 0.6);
arrowShape.lineTo(0.3, 0.6);
arrowShape.lineTo(0, 0);
const arrowGeo = new THREE.ShapeGeometry(arrowShape);
const arrowMat = new THREE.MeshBasicMaterial({ color: 0xffdd00, side: THREE.DoubleSide });
const arrowMesh = new THREE.Mesh(arrowGeo, arrowMat);
arrowGroup.add(arrowMesh);
// 화살표 막대
const arrowStickGeo = new THREE.PlaneGeometry(0.12, 0.5);
const arrowStick = new THREE.Mesh(arrowStickGeo, arrowMat);
arrowStick.position.y = 0.85;
arrowGroup.add(arrowStick);
bobberArrow = arrowGroup;
bobberArrow.visible = false;
scene.add(bobberArrow);
// 흙먼지 파티클 (물고기 도망갈 때)
const mudGeo = new THREE.SphereGeometry(0.2, 4, 4);
const mudMat = new THREE.MeshBasicMaterial({ color: 0x5c4033, transparent: true, opacity: 0.8 });
for (let i = 0; i < 8; i++) {
const p = new THREE.Mesh(mudGeo, mudMat);
p.visible = false;
scene.add(p);
mudParticles.push({ mesh: p, velocity: new THREE.Vector3(), life: 0 });
}
// 낚싯줄: 다중 점으로 자연스러운 곡선 표현 (10개 점의 catenary)
const LINE_POINTS = 12;
const lineMat = new THREE.LineBasicMaterial({ color: 0xdddddd, transparent: true, opacity: 0.6 });
const linePoints = [];
for (let i = 0; i < LINE_POINTS; i++) linePoints.push(new THREE.Vector3());
const lineGeo = new THREE.BufferGeometry().setFromPoints(linePoints);
fishingLine = new THREE.Line(lineGeo, lineMat);
fishingLine.visible = true;
fishingLine.frustumCulled = false; // 시야 밖에서도 항상 렌더링
scene.add(fishingLine);
const audioLoader = new THREE.AudioLoader();
clickSound = new THREE.Audio(audioListener);
audioLoader.load('sound/click.mp3', (buffer) => {
clickSound.setBuffer(buffer);
clickSound.setVolume(1.0);
});
waterDropSound = new THREE.Audio(audioListener);
audioLoader.load('sound/water-drop.mp3', (buffer) => {
waterDropSound.setBuffer(buffer);
waterDropSound.setVolume(1.0);
});
struggleSound = new THREE.Audio(audioListener);
audioLoader.load('sound/fish_sp.mp3', (buffer) => {
struggleSound.setBuffer(buffer);
struggleSound.setLoop(true); // 실랑이 중 계속 재생되도록 루프
struggleSound.setVolume(1.0);
});
natureSound = new THREE.Audio(audioListener);
audioLoader.load('sound/nature.mp3', (buffer) => {
natureSound.setBuffer(buffer);
natureSound.setLoop(true);
natureSound.setVolume(1.0);
if (audioStarted && !natureSound.isPlaying) natureSound.play();
});
waterWalkSound = new THREE.Audio(audioListener);
audioLoader.load('sound/grk8567-river.mp3', (buffer) => {
waterWalkSound.setBuffer(buffer);
waterWalkSound.setLoop(true);
waterWalkSound.setVolume(0.8);
});
grassWalkSound = new THREE.Audio(audioListener);
audioLoader.load('sound/grass.mp3', (buffer) => {
grassWalkSound.setBuffer(buffer);
grassWalkSound.setLoop(true);
grassWalkSound.setVolume(0.8);
});
riverSound = new THREE.PositionalAudio(audioListener);
audioLoader.load('sound/river.mp3', (buffer) => {
riverSound.setBuffer(buffer);
riverSound.setRefDistance(50);
riverSound.setRolloffFactor(1.5);
riverSound.setLoop(true);
riverSound.setVolume(1.5);
if (audioStarted && sun.visible && !riverSound.isPlaying) riverSound.play();
});
nightRiverSound = new THREE.PositionalAudio(audioListener);
audioLoader.load('sound/night-river.mp3', (buffer) => {
nightRiverSound.setBuffer(buffer);
nightRiverSound.setRefDistance(50);
nightRiverSound.setRolloffFactor(1.5);
nightRiverSound.setLoop(true);
nightRiverSound.setVolume(1.5);
if (audioStarted && moon.visible && !nightRiverSound.isPlaying) nightRiverSound.play();
});
riverAudioSource = new THREE.Object3D();
scene.add(riverAudioSource);
riverAudioSource.add(riverSound);
riverAudioSource.add(nightRiverSound);
// 브라우저 자동재생 정책 대응: 첫 클릭 시 배경음악 재생 및 안내창 숨김
document.addEventListener('click', () => {
if (audioListener.context.state === 'suspended') {
audioListener.context.resume();
}
audioStarted = true;
if (natureSound.buffer && !natureSound.isPlaying) natureSound.play();
if (sun.visible && riverSound.buffer && !riverSound.isPlaying) riverSound.play();
if (moon.visible && nightRiverSound.buffer && !nightRiverSound.isPlaying) nightRiverSound.play();
birds.forEach(bird => {
if (bird.userData.sound && bird.userData.sound.buffer && !bird.userData.sound.isPlaying) {
const distToPlayer = camera.position.distanceTo(bird.position);
if (distToPlayer < 70) {
bird.userData.sound.play();
}
}
});
const blocker = document.getElementById('blocker');
if (blocker) blocker.style.display = 'none';
}, { once: true });
// 2. 조명 (Lighting) - 초여름의 밝은 낮 시간대 (빛의 세기 20% 증가)
hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.85);
hemiLight.color.setHSL(0.6, 1, 0.6);
hemiLight.groundColor.setHSL(0.095, 1, 0.75);
hemiLight.position.set(0, 50, 0);
scene.add(hemiLight);
dirLight = new THREE.DirectionalLight(0xffffff, 1.45);
dirLight.position.set(-500, 800, -200);
dirLight.castShadow = true;
dirLight.shadow.camera.near = 0.5;
dirLight.shadow.camera.far = 1400;
// 섀도우 맵 범위 조정 (1400 맵 기준)
dirLight.shadow.camera.left = -420;
dirLight.shadow.camera.right = 420;
dirLight.shadow.camera.top = 420;
dirLight.shadow.camera.bottom = -420;
dirLight.shadow.mapSize.width = 2048;
dirLight.shadow.mapSize.height = 2048;
scene.add(dirLight);
// 2-1. 태양 (Sun) 생성 및 코로나(빛번짐) 효과
const sunGeo = new THREE.IcosahedronGeometry(40, 2);
const sunMat = new THREE.MeshBasicMaterial({
color: 0xffffff,
fog: false
});
sun = new THREE.Mesh(sunGeo, sunMat);
// 캔버스를 이용해 태양의 코로나(Glow) 텍스처 생성
const canvas = document.createElement('canvas');
canvas.width = 256;
canvas.height = 256;
const context = canvas.getContext('2d');
const gradient = context.createRadialGradient(128, 128, 0, 128, 128, 128);
gradient.addColorStop(0, 'rgba(255, 255, 255, 1.0)');
gradient.addColorStop(0.2, 'rgba(255, 250, 200, 0.8)');
gradient.addColorStop(0.5, 'rgba(255, 220, 150, 0.3)');
gradient.addColorStop(1, 'rgba(255, 200, 100, 0.0)');
context.fillStyle = gradient;
context.fillRect(0, 0, 256, 256);
const glowTexture = new THREE.CanvasTexture(canvas);
const glowMaterial = new THREE.SpriteMaterial({
map: glowTexture,
color: 0xffffee,
transparent: true,
blending: THREE.AdditiveBlending,
fog: false
});
glowSprite = new THREE.Sprite(glowMaterial);
glowSprite.scale.set(400, 400, 1); // 구체 반경(40)보다 10배 크게 번짐
sun.add(glowSprite);
// 밤하늘의 달(Moon) 생성
const moonGeo = new THREE.IcosahedronGeometry(30, 2);
const moonMat = new THREE.MeshBasicMaterial({
color: 0xddddff,
fog: false
});
moon = new THREE.Mesh(moonGeo, moonMat);
const moonPos = new THREE.Vector3(-400, 600, -300).normalize().multiplyScalar(1200);
moon.position.copy(moonPos);
moon.visible = false;
scene.add(moon);
// 밤하늘의 별(Stars) 생성
const starsGeo = new THREE.BufferGeometry();
const starsCount = 1000;
const posArray = new Float32Array(starsCount * 3);
for(let i = 0; i < starsCount * 3; i++) {
posArray[i * 3] = (Math.random() - 0.5) * 3000;
posArray[i * 3 + 1] = 200 + Math.random() * 800; // 하늘 높이
posArray[i * 3 + 2] = (Math.random() - 0.5) * 3000;
}
starsGeo.setAttribute('position', new THREE.BufferAttribute(posArray, 3));
const starsMat = new THREE.PointsMaterial({ size: 3, color: 0xffffff, transparent: true, opacity: 0.8, fog: false });
stars = new THREE.Points(starsGeo, starsMat);
stars.visible = false;
scene.add(stars);
// 광원 방향(-500, 800, -200)을 정규화하여 먼 거리에 배치
const sunPos = new THREE.Vector3(-500, 800, -200).normalize().multiplyScalar(1200);
sun.position.copy(sunPos);
scene.add(sun);
// 2-2. 하늘 구름 생성
for (let i = 0; i < 20; i++) {
const cloud = createCloud();
cloud.position.set(
(Math.random() - 0.5) * 2000,
300 + Math.random() * 200, // 높은 하늘
(Math.random() - 0.5) * 2000
);
const scale = 1.0 + Math.random() * 2.0;
cloud.scale.set(scale, scale * 0.6, scale); // 약간 납작하게
scene.add(cloud);
clouds.push(cloud);
}
// 3. 지형 (Terrain) - 1400x1400 (성능과 스케일의 균형)
const terrainSize = 1400;
// 250x250 분할 (약 6.25만 정점, 적당한 디테일)
const terrainGeo = new THREE.PlaneGeometry(terrainSize, terrainSize, 250, 250);
terrainGeo.rotateX(-Math.PI / 2);
const posAttr = terrainGeo.attributes.position;
const vertexColors = [];
for (let i = 0; i < posAttr.count; i++) {
const worldX = posAttr.getX(i);
const z = posAttr.getZ(i);
let y = getTerrainHeight(worldX, z);
let c = new THREE.Color();
const absZ = Math.abs(z);
// 지형 색상도 S자 강 형태와 완벽히 일치하도록 좌표계를 휨
const riverOffsetX = Math.sin(z * 0.006) * 180;
const x = worldX - riverOffsetX;
// X 좌표(가로)에 따른 핵심 지형 묘사
if (x < -60) {
c.setHex(0x3b5e2b); // 숲
if (y > 42 || Math.random() > 0.8) c.setHex(0x696969); // 바위 질감
}
else if (x >= -60 && x < -40) {
c.setHex(0x5c5c5c); // 회색 절벽 바위
// 바위면에 이끼(녹색)과 흙(갈색) 혼합
if (Math.random() > 0.65) c.setHex(0x4a5e3a);
else if (Math.random() > 0.5) c.setHex(0x4a4036);
}
else if (x >= -40 && x <= 70) {
c.setHex(0x6b5b45); // 진흙/돌
}
else if (x > 70 && x <= 110) {
c.setHex(0x6b5b45); // 수중은 진흙
if (y > 0) c.setHex(0x8b7d6b); // 수면 가까워지면 자갈색으로 변경
}
else if (x > 110 && x <= 140) {
c.setHex(0x8b7d6b); // 자갈색
if (Math.random() > 0.7) c.setHex(0x556b2f); // 듬성듬성 풀색 혼합
}
else if (x > 140 && x <= 400) {
const hillType = Math.floor(Math.abs(z / 180)) % 3;
if (hillType === 0) {
c.setHex(0x6b8e23); // 올리브 풀밭
if (y > 7) c.setHex(0x4a7a1e); // 언덕 꼭대기는 더 짙은 풀
} else if (hillType === 1) {
c.setHex(0x7a9e2e); // 밝은 올리브
if (Math.random() > 0.85) c.setHex(0x8b7d6b); // 듬성듬성 흙
} else {
c.setHex(0x5a7a1a); // 짙은 풀
if (y > 9) c.setHex(0x696969); // 높은 곳은 바위
}
}
else {
c.setHex(0x2e4a22); // 짙고 어두운 숲
}
// Z 좌표(앞/뒤)에 따른 먼 배경 산맥 묘사 (허공 방지)
if (absZ > 350) {
const overZ = absZ - 350;
// 멀리 있는 산은 숲/바위 색으로 덮기
c.lerp(new THREE.Color(0x3b5e2b), Math.min(overZ / 300, 1.0));
if (y > 50) c.lerp(new THREE.Color(0x696969), 0.5); // 고지대 바위
}
// 로우폴리 노이즈 추가
y += (Math.random() - 0.5) * 0.5;
posAttr.setY(i, y);
vertexColors.push(c.r, c.g, c.b);
}
terrainGeo.setAttribute('color', new THREE.Float32BufferAttribute(vertexColors, 3));
terrainGeo.computeVertexNormals();
const terrainMat = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.9,
metalness: 0.1,
flatShading: true
});
terrain = new THREE.Mesh(terrainGeo, terrainMat);
terrain.receiveShadow = true;
terrain.castShadow = true;
scene.add(terrain);
// 4. 강물 (Water)
// 강폭에 맞춰 폭을 150으로 제한 (-25 ~ 125 영역)
// 길이가 2000이므로 맵 전체를 위아래로 관통함
const waterGeo = new THREE.PlaneGeometry(150, terrainSize, 50, 200);
waterGeo.rotateX(-Math.PI / 2);
const wPosAttr = waterGeo.attributes.position;
// 강물 평면도 지형과 동일하게 S자로 굽이치도록 정점 변형
for (let i = 0; i < wPosAttr.count; i++) {
const wz = wPosAttr.getZ(i);
const riverOffsetX = Math.sin(wz * 0.006) * 180;
wPosAttr.setX(i, wPosAttr.getX(i) + riverOffsetX);
}
waterGeo.computeVertexNormals();
for (let i = 0; i < wPosAttr.count; i++) {
waterVertices.push({
x: wPosAttr.getX(i),
y: wPosAttr.getY(i),
z: wPosAttr.getZ(i)
});
}
const waterMat = new THREE.MeshStandardMaterial({
color: 0x4aa6ff,
transparent: true,
opacity: 0.5,
roughness: 0.1,
metalness: 0.2,
flatShading: true
});
water = new THREE.Mesh(waterGeo, waterMat);
water.position.set(25, 1.0, 0); // 물 객체가 x=100을 넘어 평지를 침범할 수 없도록 고정
water.receiveShadow = true;
scene.add(water);
// 5. 나무 군락 배치 — 그리드 방식 (성능 최적화 적용)
// 나무를 심을 구역 정의 (너무 많으면 브라우저가 멈추므로 spacing 최적화)
const forestZones = [
// 왼쪽 절벽 위 고지대 숲
{ xMin: -700, xMax: -65, zMin: -315, zMax: 315, spacing: 30 },
// 오른쪽 내륙 숲 (깊은 쪽)
{ xMin: 200, xMax: 700, zMin: -315, zMax: 315, spacing: 30 },
// 상류 쪽 앞 배경
{ xMin: -700, xMax: 700, zMin: 315, zMax: 665, spacing: 40 },
// 하류 쪽 뒤 배경
{ xMin: -700, xMax: 700, zMin: -665, zMax: -315, spacing: 40 },
];
for (const zone of forestZones) {
for (let tx = zone.xMin; tx < zone.xMax; tx += zone.spacing) {
for (let tz = zone.zMin; tz < zone.zMax; tz += zone.spacing) {
const localX = tx + (Math.random() - 0.5) * zone.spacing * 0.9;
const oz = tz + (Math.random() - 0.5) * zone.spacing * 0.9;
// 나무도 S자 지형 곡선을 따라 굽이치게 오프셋 적용
const riverOffsetX = Math.sin(oz * 0.006) * 180;
const worldX = localX + riverOffsetX;
// 레이캐스트 대신 수학 공식을 그대로 사용하여 연산량 10만배 감소 (렉 해결)
const ty = getTerrainHeight(worldX, oz) - 0.5;
// 50% 확률로 활엽수 또는 뾰족한 침엽수 생성
const tree = Math.random() > 0.5 ? createLowPolyTree() : createPineTree();
tree.position.set(worldX, ty, oz);
tree.rotation.y = Math.random() * Math.PI * 2;
tree.rotation.z = (Math.random() - 0.5) * 0.15;
// 최대 크기 증가 (기존: 0.8~3.0 -> 변경: 1.5~4.5)
const scale = 1.5 + Math.random() * 3.0;
tree.scale.set(scale, scale, scale);
tree.userData = {
baseRotX: tree.rotation.x,
baseRotZ: tree.rotation.z,
windSpeed: 0.4 + Math.random() * 0.6,
windOffset: Math.random() * Math.PI * 2
};
trees.push(tree);
scene.add(tree);
}
}
}
// 6. 갈대(Reed) 배치 — 물가와 자갈지대에 심기
const bushZones = [
// 물가 수풀 (갈대가 물에 살짝 닿아있는 라인)
{ xMin: 70, xMax: 120, zMin: -400, zMax: 400, spacing: 12 },
// 자갈지대 (듬성듬성)
{ xMin: 120, xMax: 150, zMin: -400, zMax: 400, spacing: 16 },
// 숲 수풀
{ xMin: 150, xMax: 200, zMin: -400, zMax: 400, spacing: 26 },
];
for (const zone of bushZones) {
for (let tx = zone.xMin; tx < zone.xMax; tx += zone.spacing) {
for (let tz = zone.zMin; tz < zone.zMax; tz += zone.spacing) {
// 72% 확률로만 심기
if (Math.random() > 0.72) continue;
const localX = tx + (Math.random() - 0.5) * zone.spacing * 0.8;
const oz = tz + (Math.random() - 0.5) * zone.spacing * 0.8;
// 갈대도 S자 지형 곡선을 따라 굽이치게 오프셋 적용
const riverOffsetX = Math.sin(oz * 0.0075) * 140;
const worldX = localX + riverOffsetX;
const by = getTerrainHeight(worldX, oz);
const bush = createBush();
bush.position.set(worldX, by, oz);
bush.rotation.y = Math.random() * Math.PI * 2;
bush.rotation.z = (Math.random() - 0.5) * 0.2;
// 물가(localX < 120)일수록 크고 높은 수풀이 많이 자라도록 확률과 크기 조정
let isLarge = false;
let largeScale = 1;
if (localX < 120) {
// 물가: 80% 확률로 크고 높은 수풀
if (Math.random() > 0.2) {
isLarge = true;
largeScale = 1.5 + Math.random() * 1.5;
}
} else if (localX < 150) {
// 자갈지대: 40% 확률로 중간 정도의 큰 수풀
if (Math.random() > 0.6) {
isLarge = true;
largeScale = 1.0 + Math.random() * 0.8;
}
} else {
// 숲(육지쪽): 10% 확률로 약간만 큰 수풀, 대부분은 기본이거나 작은 수풀
if (Math.random() > 0.9) {
isLarge = true;
largeScale = 1.0 + Math.random() * 0.4;
} else {
// 육지 쪽 기본 수풀의 크기도 조금 더 작게 설정
bush.scale.multiplyScalar(0.6 + Math.random() * 0.4);
}
}
if (isLarge) {
bush.scale.multiplyScalar(largeScale);
}
// 전체 바람 흔들림을 위해 trees 배열에 추가
bush.userData = {
baseRotX: 0,
baseRotZ: bush.rotation.z,
windSpeed: 1.5 + Math.random() * 1.5,
windOffset: Math.random() * Math.PI * 2
};
trees.push(bush);
scene.add(bush);
}
}
}
// 6. Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container.appendChild(renderer.domElement);
// 7. 마우스 조작 이벤트 (Pointer Lock 적용)
const blocker = document.getElementById('blocker');
const instructions = document.getElementById('instructions');
// 물고기 포획 메시지 UI 생성
catchMsg = document.createElement('div');
catchMsg.id = 'catch-message';
catchMsg.style.position = 'absolute';
catchMsg.style.bottom = '15%';
catchMsg.style.left = '50%';
catchMsg.style.transform = 'translateX(-50%)';
catchMsg.style.color = '#ffffff';
catchMsg.style.fontSize = '24px';
catchMsg.style.fontWeight = 'bold';
catchMsg.style.textShadow = '2px 2px 4px rgba(0,0,0,0.8)';
catchMsg.style.display = 'none';
catchMsg.style.pointerEvents = 'none';
catchMsg.style.zIndex = '100';
catchMsg.style.textAlign = 'center';
document.body.appendChild(catchMsg);
// 상호작용(아이스박스) UI
interactMsg = document.createElement('div');
interactMsg.style.position = 'absolute';
interactMsg.style.bottom = '20%';
interactMsg.style.left = '50%';
interactMsg.style.transform = 'translateX(-50%)';
interactMsg.style.color = '#ffffff';
interactMsg.style.fontSize = '24px';
interactMsg.style.fontWeight = 'bold';
interactMsg.style.textShadow = '2px 2px 4px rgba(0,0,0,0.8)';
interactMsg.style.display = 'none';
interactMsg.style.pointerEvents = 'none';
interactMsg.style.zIndex = '100';
document.body.appendChild(interactMsg);
// 아이스박스 3D 텍스트(플로팅 UI)
iceboxText = document.createElement('div');
iceboxText.style.position = 'absolute';
iceboxText.style.color = '#ffffff';
iceboxText.style.fontSize = '18px';
iceboxText.style.fontWeight = 'bold';
iceboxText.style.textShadow = '1px 1px 2px #000';
iceboxText.style.display = 'none';
iceboxText.style.pointerEvents = 'none';
iceboxText.style.zIndex = '90';
iceboxText.style.textAlign = 'center';
iceboxText.style.transform = 'translate(-50%, -100%)';
iceboxText.innerHTML = `저장된 물고기 없음`;
document.body.appendChild(iceboxText);
// 아이스박스(스폰 지점 부근) 생성 (진짜로 속이 비어있게 조립)
iceboxGroup = new THREE.Group();
const outMat = new THREE.MeshStandardMaterial({ color: 0xadd8e6, roughness: 0.5 });
const inMat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.8 });
// 1. 바닥
const baseOuter = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.05, 0.8), outMat);
baseOuter.position.y = 0.025;
iceboxGroup.add(baseOuter);
const baseInner = new THREE.Mesh(new THREE.BoxGeometry(1.1, 0.05, 0.7), inMat);
baseInner.position.y = 0.075;
iceboxGroup.add(baseInner);
// 2. 왼쪽/오른쪽 벽
const wLOut = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.8, 0.8), outMat);
wLOut.position.set(-0.575, 0.4, 0);
iceboxGroup.add(wLOut);
const wLIn = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.75, 0.7), inMat);
wLIn.position.set(-0.525, 0.425, 0);
iceboxGroup.add(wLIn);
const wROut = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.8, 0.8), outMat);
wROut.position.set(0.575, 0.4, 0);
iceboxGroup.add(wROut);
const wRIn = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.75, 0.7), inMat);
wRIn.position.set(0.525, 0.425, 0);
iceboxGroup.add(wRIn);
// 3. 앞/뒤 벽
const wFOut = new THREE.Mesh(new THREE.BoxGeometry(1.1, 0.8, 0.05), outMat);
wFOut.position.set(0, 0.4, 0.375);
iceboxGroup.add(wFOut);
const wFIn = new THREE.Mesh(new THREE.BoxGeometry(1.0, 0.75, 0.05), inMat);
wFIn.position.set(0, 0.425, 0.325);
iceboxGroup.add(wFIn);
const wBOut = new THREE.Mesh(new THREE.BoxGeometry(1.1, 0.8, 0.05), outMat);
wBOut.position.set(0, 0.4, -0.375);
iceboxGroup.add(wBOut);
const wBIn = new THREE.Mesh(new THREE.BoxGeometry(1.0, 0.75, 0.05), inMat);
wBIn.position.set(0, 0.425, -0.325);
iceboxGroup.add(wBIn);
// 그림자 일괄 적용
iceboxGroup.children.forEach(c => { c.castShadow = true; c.receiveShadow = true; });
// 뚜껑 (옆에 놓임)
const lid = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.1, 0.8), outMat);
lid.position.set(1.0, 0.05, 0);
lid.rotation.z = Math.PI / 12; // 비스듬히 놓임
lid.castShadow = true;
lid.receiveShadow = true;
iceboxGroup.add(lid);
// 위치 설정 (맵 중앙 자갈지대 부근)
iceboxGroup.scale.set(6.0, 6.0, 6.0); // 크기 대폭 확대 (6배)
iceboxGroup.position.set(113, getTerrainHeight(113, -5), -5);
scene.add(iceboxGroup);
const crosshair = document.getElementById('crosshair');
const glCanvas = renderer.domElement;
let isFirstLoad = true;
// 처음에는 크로스헤어 숨김
if (crosshair) crosshair.style.display = 'none';
// 포인터 잠금 요청 함수
const requestLock = () => {
try {
if (glCanvas.requestPointerLock) {
glCanvas.requestPointerLock();
} else if (glCanvas.mozRequestPointerLock) {
glCanvas.mozRequestPointerLock();
} else if (glCanvas.webkitRequestPointerLock) {
glCanvas.webkitRequestPointerLock();
}
} catch(err) {
console.warn('Pointer lock request failed:', err);
}
};
// 포인터 잠금 해제 함수
const releaseLock = () => {
const exitFn = document.exitPointerLock
|| document.mozExitPointerLock
|| document.webkitExitPointerLock;
if (exitFn) exitFn.call(document);
};
// blocker 클릭 → 게임 시작
blocker.addEventListener('click', (e) => {
if (e.target.tagName !== 'A') {
isFirstLoad = false;
requestLock();
}
});
// canvas 클릭해도 재개 가능
glCanvas.addEventListener('click', () => {
if (!document.pointerLockElement && !document.mozPointerLockElement) {
requestLock();
}
});
// pointerlockchange 이벤트 리스너 (파이어폭스: mozpointerlockchange)
const onPointerLockChange = () => {
const locked = !!(document.pointerLockElement || document.mozPointerLockElement);
if (locked) {
blocker.style.display = 'none';
if (crosshair) crosshair.style.display = 'block';
} else if (!isFirstLoad) {
// 최초 로드가 아닌 경우에만 일시정지 표시
blocker.style.display = 'flex';
if (crosshair) crosshair.style.display = 'none';
instructions.innerHTML = `
<span style="font-size:36px; font-weight: 900; color:#fff; margin-bottom: 20px; display:inline-block;">일시정지</span><br/><br/>
클릭하여 다시 시작합니다<br/><br/>
<b>이동:</b> W, A, S, D<br/>
<b>점프:</b> Space<br/>
<b>시야:</b> 마우스<br/>
<b>일시정지:</b> Q 키<br/><br/>
<a href="kl_earn.html" class="back-btn" style="position:relative; display:inline-block; margin-top:20px;">← 도박장으로 돌아가기</a>
`;
}
};
document.addEventListener('pointerlockchange', onPointerLockChange);
document.addEventListener('mozpointerlockchange', onPointerLockChange);
document.addEventListener('mousemove', (e) => {
const locked = !!(document.pointerLockElement || document.mozPointerLockElement);
if (locked) {
const mx = e.movementX || e.mozMovementX || 0;
const my = e.movementY || e.mozMovementY || 0;
yaw -= mx * 0.002;
pitch -= my * 0.002;
pitch = Math.max(-Math.PI/2 + 0.1, Math.min(Math.PI/2 - 0.1, pitch));
// 낚시 캐스팅 차징
if (isRodEquipped && castState === 'charging') {
const speed = Math.sqrt(mx * mx + my * my);
castPower += speed * 0.03; // 파워 누적 계수
castPower = Math.min(castPower, 45); // 최대 파워 제한
}
// 챔질(회수) 및 실랑이 로직: 마우스 클릭 중 + 시야를 위로 빠르게 올리는 동작
if (isRodEquipped && isMouseDown) {
if (['casted', 'waiting_bite', 'pre_biting'].includes(castState)) {
// 물고기 없는 상태(또는 입질/예신 대기 중)에서 일반 회수
if (my < -60) {
castState = 'idle';