- Home /
How to move object repeatedly with Vector3.MoveTowards
So now i have a boat out of the camera and i want to implement this scenario :
1- When start game, waiting for 5 seconds then move the boat from position A to position B. 2- When boat reach position B the boat will get back to position A instantly.
3- Then wait for 5 seconds again and repeat 1 and 2 steps
And so on ..
This is my code but the problem that when start the game, the boat starting move without waiting seconds and once it reach to position B it get moved again and also increase its speed.
// Use this for initialization
void Start () {
startPos = transform.position;
moveBoats = MoveBoats ();
}
// Update is called once per frame
void Update () {
StartCoroutine (moveBoats);
if (transform.position.x == boatEndPoint.transform.position.x) {
transform.position = startPos;
}
}
IEnumerator MoveBoats ()
{
while (true) {
yield return new WaitForSeconds (5.0f);
transform.position = Vector3.MoveTowards (transform.position, boatEndPoint.transform.position, speed * Time.deltaTime);
}
}
How can i fix that ??
Answer by SohailBukhari · Jul 17, 2017 at 07:01 AM
in the Start method just pass the points a and b and and time to move.Lets suppose you want to move from point a to point b within 5 seconds then yield return StartCoroutine(MoveObject(transform, pointA, PointB, 5.0f));
public Vector3 PointB;
IEnumerator Start()
{
var pointA = transform.position;
while (true)
{
yield return StartCoroutine(MoveObject(transform, pointA, PointB, 3.0f));
yield return StartCoroutine(MoveObject(transform, PointB, pointA, 3.0f));
}
}
IEnumerator MoveObject(Transform thisTransform, Vector3 startPos, Vector3 endPos, float time)
{
yield return new WaitForSeconds(5f);// first yield return after five seconds as you want
var i = 0.0f;
var rate = 1.0f / time;
while (i < 1.0f)
{
i += Time.deltaTime * rate;
thisTransform.position = Vector3.Lerp(startPos, endPos, i);
yield return null;
}
}
Arrange time when your boat come and at which speed.
you can also use MoveTowards Scripting API to move.