//1.实现 move(GameObject gameObject, Vector3 begin, Vector3 end, float time, bool pingpong){}
//使gameObject在time秒内,从begin移动到end,若pingpong为true,则在结束时使gameObject在time秒内从end移动到begin,如此往复。
//2.在上题基础上实现 easeIn easeOut easeInOut 动画效果
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovePosition : MonoBehaviour
{
public enum EaseType
{
None = 0,
EaseIn = 1,
EaseOut = 2,
EaseInOut = 3,
}
private GameObject _targetGameObject;
private Vector3 _startPos;
private Vector3 _endPos;
private float _totalMoveTime;
private float _elapsedTime;
private bool _isMovingForward = true;
public bool isPingPong;
public EaseType _easeType = EaseType.None;
// Start is called before the first frame update
void Start()
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Sphere);
Vector3 begin = new Vector3(-10, 0, 0);
Vector3 end = new Vector3(10, 0, 0);
float moveTime = 2f;
bool pingpong = true;
move(cube, begin, end, moveTime, pingpong,_easeType);
}
private void move(GameObject gameObject, Vector3 begin, Vector3 end, float time, bool pingpong, EaseType et)
{
_targetGameObject = gameObject;
_startPos = begin;
_endPos = end;
_totalMoveTime = time;
isPingPong = pingpong;
_elapsedTime = 0f;
_isMovingForward = true;
}
// Update is called once per frame
void Update()
{
if (_targetGameObject == null) return;
_elapsedTime += Time.deltaTime;
// 计算当前移动的进度,范围在 0 到 1 之间
float t = Mathf.Clamp01(_elapsedTime / _totalMoveTime);
// 使用 easeIn 缓动函数
t = MoveType(_easeType,t);
if (_isMovingForward)
{
// 从 begin 移动到 end
_targetGameObject.transform.position = Vector3.Lerp(_startPos, _endPos, t);
}
else
{
// 从 end 移动到 begin
_targetGameObject.transform.position = Vector3.Lerp(_endPos, _startPos, t);
}
if (t >= 1f)
{
if (isPingPong)
{
// 切换移动方向
_isMovingForward = !_isMovingForward;
_elapsedTime = 0f;
}
else
{
// 如果不进行往返移动,停止移动
_targetGameObject = null;
}
}
}
private float MoveType(EaseType et, float t)
{
float _t = t;
switch (et)
{
case EaseType.EaseIn:
_t = EaseIn(t);
break;
case EaseType.EaseOut:
_t = EaseOut(t);
break;
case EaseType.EaseInOut:
_t = EaseInOut(t);
break;
default:
break;
}
return _t;
}
// EaseIn 缓动函数
private float EaseIn(float t)
{
return t * t;
}
// EaseOut 缓动函数
private float EaseOut(float t)
{
return 1 - Mathf.Pow(1 - t, 2);
}
// EaseInOut 缓动函数
private float EaseInOut(float t)
{
return t < 0.5f ? 2 * t * t : -1 + (4 - 2 * t) * t;
}
}
题1和2答案-Move的实现带有easeIn easeOut easeInOut 动画效果
于 2025-03-06 11:43:38 首次发布