- Home /
Having trouble getting Vector2.MoveTowards to work
Essentially what I'm trying to do is move my object from its starting position to a different "Y" position but keeping the same "X" position. Here is my code.
private Vector2 currentPos;
private Vector2 newPos;
// Use this for initialization
void Start () {
currentPos = new Vector2 (transform.position.x, transform.position.y);
newPos = new Vector2 (transform.position.x, Random.Range (3.0f, 4.7f));
}
// Update is called once per frame
void Update () {
transform.position = Vector2.MoveTowards (currentPos, newPos, 1f * Time.deltaTime);
}
I can't seem to get it to work at all. Any suggestions? Thanks!
add more in maxDistanceDelta, change 1f to something bigger
change this line.... transform.position = Vector2.$$anonymous$$oveTowards (currentPos, newPos, 1f * Time.deltaTime);
TO transform.position = Vector2.$$anonymous$$oveTowards (transform.position, newPos, 1f * Time.deltaTime);
And you're done !!
Hope this helps
$$anonymous$$oveTowards is exactly what I needed. Thanks everyone!! :)
Perfect, can you convert my comment to the answer, if it helped you out? Thanks.
Answer by zohaib817 · Jul 13, 2015 at 01:39 PM
private Vector2 currentPos; private Vector2 newPos;
// Use this for initialization
void Start () {
currentPos = new Vector2 (transform.position.x, transform.position.y);
}
// Update is called once per frame
void Update () {
newPos = new Vector2 (transform.position.x, Random.Range (3.0f, 4.7f));
transform.position = Vector2.MoveTowards (currentPos, newPos, 1f * Time.deltaTime);
}
try this :)
Your answer
![](https://koobas.hobune.stream/wayback/20220611231014im_/https://answers.unity.com/themes/thub/images/avi.jpg)