using UnityEngine;
public class Oscillator : MonoBehaviour
{
[Header("Settings")]
[SerializeField] private Vector3 movementVector;
[SerializeField] private float moveSpeed;
private Vector3 startPosition;
private Vector3 endPosition;
private float movementFactor;
void Start()
{
startPosition = transform.position;
endPosition = startPosition + movementVector;
}
void Update()
{
movementFactor = Mathf.PingPong(Time.time * moveSpeed, 1f);
transform.position = Vector3.Lerp(startPosition, endPosition, movementFactor);
}
}
이 Oscillator 클래스는 오브젝트를 특정 방향으로 왕복 운동(Oscillation) 시키는 기능을 한다.
오브젝트가 movementVector 방향으로 움직였다가 다시 원래 위치로 돌아오는 과정을 반복하는 것이다.
이동할 위치와 속도는 인스펙터에서 설정한다.
movementFactor = Mathf.PingPong(Time.time * moveSpeed, 1f);
- Mathf.PingPong(float t, float length)
- t: 시간(Time.time)에 moveSpeed를 곱해 증가하는 값
- length: 최대값을 의미 (1f로 설정)
- 이 함수는 t 값을 0에서 length 사이에서 왕복하도록 한다.
- 결과적으로, movementFactor 값은 0에서 1 사이에서 반복적으로 증가했다 감소한다.
1. 왕복 운동을 위한 movementFactor 계산
// moveSpeed가 2일 때
Time.time = 0 → PingPong(0, 1) = 0
Time.time = 0.5 → PingPong(1, 1) = 1
Time.time = 1 → PingPong(2, 1) = 0
Time.time = 1.5 → PingPong(3, 1) = 1
- movementFactor 값이 0 → 1 → 0 → 1 반복적으로 변한다.
- moveSpeed 값을 올리면 더 빠르게 왕복한다.
2. 보간(Lerp)를 이용한 이동
transform.position = Vector3.Lerp(startPosition, endPosition, movementFactor);
- Vector3.Lerp(A, B, t)
- A: 시작 위치
- B: 끝 위치
- t: 0~1 사이의 보간 계수 (0이면 A, 1이면 B, 0.5면 중간)
- movementFactor 값이 0에서 1로 변할 때, transform.position이 startPosition에서 endPosition으로 이동한다.
- movementFactor 값이 다시 1에서 0으로 줄어들면, 다시 startPosition으로 되돌아온다.
movementFactor = 0 → Lerp(start, end, 0) → start 위치
movementFactor = 0.5 → Lerp(start, end, 0.5) → 중간 위치
movementFactor = 1 → Lerp(start, end, 1) → end 위치
이런 식으로 보간을 통해 부드러운 왕복 운동이 구현된다.
'유니티' 카테고리의 다른 글
| [유니티] Time Line (타임 라인) (0) | 2025.03.27 |
|---|---|
| [유니티6] 새로운 Input System (0) | 2025.03.26 |
| [유니티] 파티클 시스템 (0) | 2025.03.24 |
| [유니티6] Cinemachine Camera(시네머신 카메라) (0) | 2025.03.22 |
| [유니티] #6 수박 게임 만들기 (코루틴, 랜덤 확률, Line Renderer) (0) | 2025.03.17 |