This is my first time asking a question. Please be patient with me.
I am a beginner in using C# and unity.
I’m testing few stuff right now.
I have an object that is located somewhere in the scene. I am trying to move it to the scene origin point (0,0) and then return to the original position.
I am trying to do it while using Coroutine because I want it to move then comeback and then move again.
However, the object movement is not right.
- The first movement looks good, but all the other movement are not right
- in the second loop, it never reaches it target because of the decimals in the
x,yandzfloatvalues.
My code is below. I apprecaite if anyone can guide me.
public class ObjectB : MonoBehaviour
{
public float speed;
public float seconds;
public Vector2 originPos;
public Vector2 currentPos;
public Vector2 targetPos1;
public Vector2 targetPos2;
public float step;
void Start()
{
originPos = transform.position;
}
private void Update()
{
currentPos = transform.position;
StartCoroutine(MoveBehaviour());
}
public IEnumerator MoveBehaviour()
{
yield return Movement(targetPos1);
yield return new WaitForSeconds(seconds);
yield return Movement(originPos);
yield return new WaitForSeconds(seconds);
yield return Movement(targetPos1);
yield return new WaitForSeconds(seconds);
yield return Movement(originPos);
yield return new WaitForSeconds(seconds);
}
public IEnumerator Movement(Vector2 target)
{
while (currentPos != target)
{
transform.position = Vector2.MoveTowards(transform.position, target, speed*Time.deltaTime);
yield return null;
}
}
}
I need to mention also that the speed of the object is increasing significantly after each coroutine and it does no longer wait for seconds which makes me believe it’s calling all of them at the same time.
EDIT:
I fixed it partially by calling it at Start and not Update. However I have another problem now. the object is moving back and fourth only once.
Can someone explain please why is this happening?
EDIT2:
I fixed the issue by calling currentPosition at start also.
As you mentioned, comparing float values like this
– Ady_Mnum1 != num2,vec1 != vec2can be unreliable. Instead, you should check if the values are too far apart:Mathf.Abs(num1 - num2) > 0.0001,Vector2.Distance(vec1, vec2) > 0.0001,(vec1 - vec2).magnitude > 0.0001. When you solve the problem yourself, please post an answer and mark it as the solution.