今日已更新 68 条资讯 | 累计 21557 条内容
关于我们

Oscillation, Mathf.PingPong, Vector3.Lerp

Giorgi Eliozashvili 2026年07月19日 17:17 1 次阅读 来源:Dev.to

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 ); } } 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

本文内容来源于互联网,版权归原作者所有
查看原文