DEV Community

Khandokar Nafis Jaman
Khandokar Nafis Jaman

Posted on

Slowly move gameobject from one place to another in Unity3D

Sometimes we need to move a game object from one place to another and maintain the speed of movement. Vector3.MoveTowards() can be the perfect solution for this. We need to create an empty gameobject and set the position where we need to move our gameobject. Then create another empty gameobject and make the previous two gameobject of it's child.
Let's say, we need to move DonkeyKong gameobject to the position of platformB. Then it can be like this.

Image description

Then, create a scripts, attach to the parent object and paste the following code.

`using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlatformMovement : MonoBehaviour
{
private Vector3 pointA;
private Vector3 pointB;
Vector3 nextPos;
[SerializeField] float speed;
[SerializeField] Transform childTransform;
[SerializeField]
Transform transformB;
// Start is called before the first frame update
void Start()
{
pointA = childTransform.localPosition;
pointB = transformB.localPosition;
nextPos = pointB;
}

// Update is called once per frame
void Update()
{
    Move();
}

void Move()
{
    childTransform.localPosition = Vector3.MoveTowards(childTransform.localPosition, nextPos, speed*Time.deltaTime);

}
Enter fullscreen mode Exit fullscreen mode

}
`

Then, set the variables to the inspector.

Image description

If we want to move gameobject in a periodic motion, we need to add a couple of lines.

`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlatformMovement : MonoBehaviour
{
private Vector3 pointA;
private Vector3 pointB;
Vector3 nextPos;
[SerializeField] float speed;
[SerializeField] Transform childTransform;
[SerializeField]
Transform transformB;
// Start is called before the first frame update
void Start()
{
pointA = childTransform.localPosition;
pointB = transformB.localPosition;
nextPos = pointB;
}

// Update is called once per frame
void Update()
{
    Move();
}

void Move()
{
    childTransform.localPosition = Vector3.MoveTowards(childTransform.localPosition, nextPos, speed*Time.deltaTime);
  //check if the position of gameobject is changed  if(Mathf.Abs(Vector3.Distance(childTransform.localPosition, nextPos) ) <= .1f)
    {
        ChangeDestination();
    }
}

void ChangeDestination()
{
  //set the next position
    nextPos = nextPos != pointA ? pointA : pointB;
}
Enter fullscreen mode Exit fullscreen mode

}

`

Top comments (0)