The reason why I need to use a coroutine for the rotation is that the object I throw to the target will move to the target and back once and then when the object return back I want the object also to be rotating facing forward but to be rotating smoothly slowly. first, I want the object to look at the target rotate to the target smooth slowly in the Throw method then in the ThrowBack method to rotate facing the parent.
I'm using coroutines because I want to make things once. for example, move to the target and back and then rotate but if I will make the rotation in the update it will keep rotating and I need the object to be able to rotate later too so I think it's better to make the rotation in a coroutine.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThrowObject : MonoBehaviour
{
public Transform objectToThrow;
public Transform target;
public Transform objectToThrowParent;
public float throwingSpeed;
public bool go = false;
private Animator anim;
private bool startThrowAnimationOnce = true;
private Vector3 originPos;
private void Start()
{
anim = GetComponent<Animator>();
originPos = objectToThrowParent.position;
}
private void Update()
{
if (anim != null && startThrowAnimationOnce))
{
anim.SetTrigger("Throw");
startThrowAnimationOnce = false;
}
if (go)
{
objectToThrow.parent = null;
StartCoroutine(Throw());
go = false;
}
}
public void ThrowEvent()
{
go = true;
}
IEnumerator Throw()
{
while (objectToThrow.position != target.position)
{
objectToThrow.position = Vector3.MoveTowards(
objectToThrow.position,
target.position,
throwingSpeed * Time.deltaTime
);
yield return null;
}
objectToThrow.position = target.position;
yield return new WaitForSeconds(10f);
StartCoroutine(ThrowBack());
}
IEnumerator ThrowBack()
{
while (objectToThrow.position != objectToThrowParent.position)
{
objectToThrow.position = Vector3.MoveTowards(
objectToThrow.position,
objectToThrowParent.position,
throwingSpeed * Time.deltaTime
);
yield return null;
}
objectToThrow.position = objectToThrowParent.position;
objectToThrow.parent = objectToThrowParent;
objectToThrow.localPosition = new Vector3(0, 0, 0);
//objectToThrow.localRotation = Quaternion.Euler(0, 0, 0);
}
}
```