-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlerp.js
More file actions
54 lines (49 loc) · 2.3 KB
/
Copy pathlerp.js
File metadata and controls
54 lines (49 loc) · 2.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
// [수학 & 모션 공식] Linear Interpolation (lerp)
// 설명: 두 값 사이를 t(0~1) 비율로 보간. 부드러운 전환의 기본 공식
// 팁: t 값이 클수록 빠르게 따라감 (0.01=느림, 0.5=빠름). 매 프레임 호출해야 부드러움. 프레임레이트 독립적으로 만들려면 deltaTime을 곱하거나 1 - (1-t)^dt 형태로 사용.
// 마우스를 추적할 컨테이너
const container = document.getElementById('lerpContainer');
// 마우스를 부드럽게 따라갈 요소
const follower = document.getElementById('follower');
// 실시간 마우스 위치(목표) 표시
const target = document.getElementById('target');
// t 값을 조절할 슬라이더
const tSlider = document.getElementById('lerpT');
// t 현재값 표시 텍스트
const tVal = document.getElementById('lerpTVal');
// 마우스 좌표 (목표 위치)
let mouseX = 150, mouseY = 150;
// 현재 follower 위치 (lerp로 mouseX/Y에 점진적으로 수렴)
let currentX = 150, currentY = 150;
// 선형 보간: t=0이면 a, t=1이면 b, 그 사이는 비례
function lerp(a, b, t) {
// a + (b-a)*t = a에서 b 방향으로 t 비율만큼 이동한 값
return a + (b - a) * t;
}
// 슬라이더 입력 시 화면 표시 갱신
tSlider.addEventListener('input', () => tVal.textContent = tSlider.value);
// 마우스 이동: 목표 좌표만 갱신
container.addEventListener('mousemove', (e) => {
const rect = container.getBoundingClientRect();
// 컨테이너 내부 좌표로 변환
mouseX = e.clientX - rect.left;
mouseY = e.clientY - rect.top;
});
// 매 프레임 follower를 마우스 쪽으로 lerp 이동
function animate() {
// 슬라이더에서 현재 t값 읽기 (작을수록 천천히 따라감)
const t = parseFloat(tSlider.value);
// 현재값을 마우스 방향으로 t비율만큼 이동 → 매 프레임 거리의 t만큼 줄어들어 점근적 수렴
currentX = lerp(currentX, mouseX, t);
currentY = lerp(currentY, mouseY, t);
// 부드러운 follower 위치 업데이트
follower.style.left = currentX + 'px';
follower.style.top = currentY + 'px';
// 즉시 반응하는 target은 정확한 마우스 위치
target.style.left = mouseX + 'px';
target.style.top = mouseY + 'px';
// 다음 프레임 예약
requestAnimationFrame(animate);
}
// 애니메이션 루프 시작
animate();