Как работает Quaternion Lerp?
Есть код. Нужно, чтобы при входе в триггер MainPipe.Pipe плавно сбрасывал свой rotation с текущего значения на (0,0,0). Но rotation сбрасывается мгновенно. Ошибка, наверное, где то в методе Landing? По Lerp смотрела видео и документацию. Вроде бы, все правильно сделала, но ошибка где то есть, а я ее не вижу
private float _landingSpeed = 0.5f;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
StartCoroutine(LandingCoroutine());
}
}
IEnumerator LandingCoroutine()
{
while (MainPipe.Pipe.transform.rotation.x != 0)
{
Landing();
}
if(MainPipe.Pipe.transform.rotation.x == 0)
{
StopCoroutine(LandingCoroutine());
}
yield return new WaitForSeconds(0.1f);
}
private void Landing()
{
Quaternion.Lerp(MainPipe.Pipe.transform.rotation, MainPipe.Pipe.transform.rotation = Quaternion.Euler(0,0,0), _landingSpeed);
}
Ответы (1 шт):
Помимо того, что я написал в комменте. Извне изменять состояние объекта (менять поля и т.д.) не самая лучшая идея, т.к. его могут изменять из разных мест и понять откуда появился какой-то баг будет сложнее. Он должен сам свое состояние изменять.
Что-то вроде:
using System.Collections;
using UnityEngine;
namespace Assets.Scripts.Pipes
{
public class Pipe : MonoBehaviour
{
[Header("Angles/second")]
[SerializeField] private float _landingRotationSpeed = 10f;
private Quaternion _landingRotation = Quaternion.identity;
private IEnumerator _landingCoroutine = null;
public void Land()
{
if (_landingCoroutine == null)
{
_landingCoroutine = Rotate(_landingRotation, _landingRotationSpeed);
StartCoroutine(_landingCoroutine);
}
}
private IEnumerator Rotate(Quaternion rotation, float speed)
{
while (transform.rotation != rotation)
{
var newRotation = Quaternion.RotateTowards(transform.rotation, rotation, speed * Time.deltaTime);
transform.rotation = newRotation;
yield return null;
}
_landingCoroutine = null;
}
}
}
Теперь не нужно изменять rotation извне, достаточно вызвать метод Land, чтобы его вращение обнулилось. Вот так:
using UnityEngine;
namespace Assets.Scripts.Pipes
{
public class LandingZone : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.TryGetComponent(out Pipe pipe))
{
pipe.Land();
}
}
}
}
При входе в триггер, пытаемся получить компонент Pipe и вызвать метод Land. И не нужно никаких Mainpipe.pipe.transform.rotation...........
Если так нужен Lerp, то замени в этой строке var newRotation = Quaternion.RotateTowards(transform.rotation, rotation, speed * Time.deltaTime); RotateTowards на Lerp, соответственно speed нужно будет ограничить от 0 до 1.