- Home /
How do I use MoveTowards in 2d?
I am trying to get this object to move toward the position slowly and stop moving when it is there.
here is the script
public Vector2 aPosition0 = new Vector2(0, 0);
public Vector2 aPosition1 = new Vector2(0, 0);
void Update ()
{
Vector2.MoveTowards(aPosition0, aPosition1, 10 * Time.deltaTime);
}
going to be a it slow to respond because I well probably be asleep
Try this one brother! hope it helps
private Vector3 target ;
public GameObject position1;
public float speed =1 ;
void Update ()
{
target = position1.transform.position;
target.z = transform.position.z;
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, target, speed * Time.deltaTime);
}
I took out the transform.position but I just added it back in and it seemed to work.
Answer by iamthecoolguy11 · Sep 09, 2014 at 11:40 AM
Ok I got it working here is it fixed
public Vector2 aPosition1 = new Vector2(3,3);
void Update ()
{
transform.position = Vector2.MoveTowards(new Vector2(transform.position.x, transform.position.y), aPosition1, 3 * Time.deltaTime);
}
3 days searching for the right way to use $$anonymous$$oveTowards thanks a lot mate!
This works great for what I'm trying to do, except I want the transform to move only along the x-axis. right now the transform is following the player even along the y-axis, when the player is jumping, but I want it to stay on the ground. How can I set his y-position to a constant value?
private void Update()
{
playerPos = new Vector2(Player.position.x, Player.position.y);
float playerDistance = Vector2.Distance(transform.position, Player.position);
print("Distance from Enemy to Player: " + playerDistance);
if (playerDistance <= $$anonymous$$axDist)
{
transform.position = Vector2.$$anonymous$$oveTowards(new Vector2(transform.position.x, transform.position.y), playerPos, $$anonymous$$oveSpeed * Time.deltaTime);
// transform.position = new Vector2(Player.position.x, transform.position.y) *$$anonymous$$oveSpeed * Time.deltaTime;
}
}
I know this is really late but you could just add a Rigidbody2D to the desired object. This is stupid because you probably found an answer so yeah... bye
Your answer
![](https://koobas.hobune.stream/wayback/20220613162622im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
What is wrong with my Counter Script? (C#) 1 Answer
Distribute terrain in zones 3 Answers
Using Texture Assets in Code 1 Answer
Multiple Cars not working 1 Answer