진동, Mathf.PingPong, Vector3.Lerp

작성자

카테고리:

← 피드로
DEV Community · Giorgi Eliozashvili · 2026-07-19 개발(SW)
Cover image for Oscillation, Mathf.PingPong, Vector3.Lerp

Giorgi Eliozashvili

When you develop a game at the beginning of your journey, you quickly notice that the environment is very static. To change that, let’s create some oscillations and move our platforms.

We will use methods like Vector3.Lerp and Mathf.PingPong.

using UnityEngine;

public class Oscillate : MonoBehaviour
{
    [SerializeField] private Vector3 movementVector;
    [SerializeField] private float speed;

    private Vector3 _startPosition;
    private Vector3 _endPosition;
    private float _movementFactor;

    private void Start()
    {
        _startPosition = transform.position;
        _endPosition = transform.position + movementVector;
    }

    private void Update()
    {
        _movementFactor = Mathf.PingPong(Time.time * speed, 1f);
        transform.position = Vector3.Lerp(_startPosition, _endPosition, _movementFactor);
    }
}

Enter fullscreen mode Exit fullscreen mode

First, we add movementVector and speed to inspector. movementVector receives the direction, and we tell it how far object must move. speed defines how fast objects move

_startPosition simply gets the starting coordinates in Start() with transform.position, and _endPosition is the sum of the _startPosition and movementVector.

Now _movementFactor is different. It defines the progress of the movement. Imagine it as a loading bar from 1% to 100%. In Update() method, we constantly calculate it every frame using Mathf.PingPong

_movementFactor = Mathf.PingPong(Time.time * speed, 1f);

So what is going on here, Mathf.PingPong does what you would imagine. Value goes back and forth. 1f is our length, so in Update() every frame _movementFactor is getting updated from 0.0, 0.1, 0.2… up to 1.0, when the value is 1.0, it goes back to 0.0 in the same way. And since it’s in Update() this is an endless cycle.

transform.position = Vector3.Lerp(_startPosition, _endPosition, _movementFactor);

Now this is where magic happens. Lerp (Linear Interpolation) takes start position, end position and a “loading” bar. Why we did exactly 1f in PingPong is perfectly described in the official documentation:

a — _startPosition

b — _endPosition

Value used to interpolate between a and b. Values greater than one are clamped to 1. Values less than zero are clamped to 0.

In short, Lerp is teleporting an object by a very short amount, and to our eyes, it looks like smooth movement.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다