- Home /
Unit rotation fails consistently on all slerp rotations after the first?
I'm working on a small project where my units need to move around on a 2D board, facing their movement directions before they do.
I've got it to a point where the first time someone clicks on the map, the unit rotates smoothly towards the target and then moves. However, after that - all subsequent rotations only rotate a portion of the way. I'm not sure what if anything is wrong with my code to cause that.
It takes place in a coroutine, and while loop. Here is a visual example:
This is the code I have thus far. It's possible that I'm not resetting something, but I'm not sure what as most of the variables are self-contained.
public Transform _transform;
public Vector3 CurrentTarget;
public Quaternion TargetRotation;
private bool canMove = true;
private bool isRotating = false;
public float lerpDurationTime = 2f;
// Start is called before the first frame update
void Start()
{
_transform = transform;
}
public void Move(Vector3 TargetPosition)
{
if (canMove) {
if (CurrentTarget != TargetPosition) {
CurrentTarget = TargetPosition;
}
if (LookingAtTarget(CurrentTarget)) {
Tween.Position(_transform, CurrentTarget, 2, 0, Tween.EaseLinear, Tween.LoopType.None, null, () => {
canMove = true;
});
canMove = false;
} else {
TargetRotation = Quaternion.LookRotation(-CurrentTarget - _transform.position, Vector3.up);
StartCoroutine(LerpRotation(2));
}
}
}
IEnumerator LerpRotation(float duration)
{
float time = 0;
Quaternion startValue = transform.rotation;
while (time < duration) {
transform.rotation = Quaternion.Slerp(startValue, TargetRotation, time / duration);
time += Time.deltaTime;
yield return null;
}
transform.rotation = TargetRotation;
Move(CurrentTarget);
}
private bool LookingAtTarget(Vector3 target)
{
float angle = 5;
if (Vector3.Angle(-_transform.forward, target - _transform.position) < angle) {
return true;
}
return false;
}
Comment