- Home /
Question by
Kuro_tsuki · Mar 07 at 08:16 AM ·
coroutinemovetowards
Question about Vector3.MoveTowards using Coroutine
I have a question about my coding which I using MoveTowards and coroutine to move the spike up and down repeatedly. When game start, the spike will wait for 5 second and going up. Once it reach the destination, it will wait for 5 seconds and going down.
This is my code. The problem is that the spike move smoothly about 2-4 times then it start vibing when going to the destination.
void Start()
{
initPos = new Vector3(transform.position.x, -4, transform.position.z);
finalPos = new Vector3(transform.position.x, -2, transform.position.z);
}
void Update()
{
StartCoroutine(Trap());
}
IEnumerator Trap()
{
if(transform.position != finalPos && count == 0)
{
yield return new WaitForSeconds(upTime);
transform.position = Vector3.MoveTowards(transform.position, finalPos, Time.deltaTime * speed);
if(transform.position == finalPos)
{
count = 1;
}
}
if(transform.position != initPos && count == 1)
{
yield return new WaitForSeconds(downTime);
transform.position = Vector3.MoveTowards(transform.position, initPos, Time.deltaTime * speed);
if(transform.position == initPos)
{
count = 0;
}
}
}
trap.png
(40.5 kB)
Comment
Best Answer
Answer by sacredgeometry · Mar 07 at 08:19 AM
Start your coroutine once, on start and put the logic in the coroutine in a loop which yield returns each iteration.