using Vector2 Movetowards not working

Hey all, i know this is probably something very simple, but i have a game object that will just be an NPC, moving to 4 points on the 2d top down, and used something similar to:

howevever in my code below, I have an Vector 2 Array, that has 2 (total 3 if you count the zero), locations including home vector 2, and depending where or what vector the npc/game object is, move to the next one, however, it never leaves the home, I do have a debug on it, and it does show up in the console, however the 2d object never moves, it does have a box collider 2d on it, doesnt have a rigid body, which i tried, but still doesnt move… any ideas?

    void MoveCharacter(float steps)
    {
        //Move X first, then move Y
        Debug.Log("Moving!");
        if(currentPosition == homePosition)
        {
            this.transform.position = Vector2.MoveTowards(transform.position, targetPosition[0], steps);
            Debug.Log("Moving to first spot!");
        }
        if(currentPosition == targetPosition[0])
        {
            this.transform.position = Vector2.MoveTowards(transform.position, targetPosition[1], steps);
        }
        if (currentPosition == targetPosition[1])
        {
            this.transform.position = Vector2.MoveTowards(transform.position, targetPosition[2], steps);
        }
        else
        {
            this.transform.position = Vector2.MoveTowards(transform.position, homePosition, steps);
        }
    }

    private void Update()
    {
        float moveSteps = moveSpeed * Time.deltaTime;
        if (TimeToMoveCountdown >= 0.0f)
        {
            TimeToMoveCountdown -= Time.deltaTime;
        }
        else
        {
            MoveCharacter(moveSteps);
            TimeToMoveCountdown = OGTimeToMoveCountdown;
        }
    }

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

You must find a way to get the information you need in order to reason about what the problem is.

ok so I took the MoveTowards method out of the if statement, now it works, i am even more confused now… because it does go to the Debug.Log, … so am i missing something???

code:

 private void Update()
    {
        float moveSteps = moveSpeed * Time.deltaTime;
        this.transform.position = Vector2.MoveTowards(transform.position, targetPosition[0], moveSteps);
        if (TimeToMoveCountdown >= 0.0f)
        {
            TimeToMoveCountdown -= Time.deltaTime;
        }
        else
        {
            if (currentPosition == homePosition)
            {
                this.transform.position = Vector2.MoveTowards(transform.position, targetPosition[0], moveSteps);
                Debug.Log("Moving to first spot!");
            }
            if (currentPosition == targetPosition[0])
            {
                this.transform.position = Vector2.MoveTowards(transform.position, targetPosition[1], moveSteps);
            }
            if (currentPosition == targetPosition[1])
            {
                this.transform.position = Vector2.MoveTowards(transform.position, targetPosition[2], moveSteps);
            }
            else
            {
                this.transform.position = Vector2.MoveTowards(transform.position, homePosition, moveSteps);
            }
            TimeToMoveCountdown = OGTimeToMoveCountdown;
        }
    }

the other thing i am noticing, is its not going in the direction i want, it goes waaaaay off the map, and keeps going, i always thought it went from 1 point to another??? is that not the purpose of this method?

I just want a game object that goes from starting position, to ending position…

You shouldn’t be comparing Vector3 quantities for equality. Here’s why:

https://starmanta.gitbooks.io/unitytipsredux/content/floating-point.html

If you’re doing those checks to test for some kind of game state, such as “I’m at home, I’m at position 0, I’m at position 1”, it’s always better to ignore the positions and explicitly track that, perhaps with an enum.

Otherwise you risk thinking something is at home when in fact it’s a fraction of a unit away from home, or it steps right over home as it goes by.

k thank you for that, i think now with the enum, i can set position by int’s like you said, also, the other thing is, I see my character is at x: -1503.09 and y: -690.76 so when it does move, it keeps on going negative, so moving away from target position, rather than go to it… any idea?

sorry the target position should be X: -1466.42 and y: -690.76, meaning it should just go horizontally, but it just goes diagonally endlessly.

Start printing values of what you’re moving it by.

All the above code looks (at least to me) like it’s just a waypoint follower, home to 0 to 1 to 2

There’s no need to code it like that with if/else statements.

Instead have an index into the array of waypoints, telling which waypoint you’re working on.

  • Set the waypoint position to be your desiredPosition
  • move the currentPosition towards it
  • Update the index when you reach it
  • repeat until end of waypoints

Generally:

Smoothing movement between any two particular values:

https://discussions.unity.com/t/812925/5

You have currentQuantity and desiredQuantity.

  • only set desiredQuantity
  • the code always moves currentQuantity towards desiredQuantity
  • read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

The code: https://gist.github.com/kurtdekker/fb3c33ec6911a1d9bfcb23e9f62adac4

For score count-up (like a cash register whizzing lots of numbers upwards), I like this approach:

https://discussions.unity.com/t/879707/2

gotya, also, one other thing, MoveTowards, just moves, does it stop once it reaches the other Vector?

You can get most of the information you need just by reading the documentation for MoveTowards.

To answer your question using a quote from the page, “If the current position is already closer to the target than maxDistanceDelta, the value returned is equal to target; the new position does not overshoot target.”