Object following on Y axis but not relative to speed variable

Hey, I am trying to make a Pong AI that follows the ball on the Y axis in order to defend from getting scored on. The problem is, no matter what value I set it’s speed variable too, it will always go as fast as it has to in order to defend the ball from reaching the goal, which isn’t what I’m aiming for because this obviously doesn’t let the player ever score. Can someone tell me why it doesn’t take in regard the speed variable?

Your usage of Vector2.MoveTowards looks correct to me.

I’m not 100% sure without going and testing it myself, but if we look at the function for Vector2.MoveTowards from Unity’s source code, I would guess you are just not setting the speed value high enough:

public static Vector2 MoveTowards(Vector2 current, Vector2 target, float maxDistanceDelta)
    // avoid vector ops because current scripting backends are terrible at inlining
    float toVector_x = target.x - current.x;
    float toVector_y = target.y - current.y;

    float sqDist = toVector_x * toVector_x + toVector_y * toVector_y;

    if (sqDist == 0 || (maxDistanceDelta >= 0 && sqDist <= maxDistanceDelta * maxDistanceDelta))
        return target; // I am guessing this is being hit

    float dist = (float)Math.Sqrt(sqDist);

    return new Vector2(current.x + toVector_x / dist * maxDistanceDelta,
        current.y + toVector_y / dist * maxDistanceDelta);

If your step variable is large enough to where the difference in positions is less than step (which for you is speed * Time.deltaTime), then it will go straight to the target, which makes sense.

Some things to try:

  • What’s the lowest value you have tried setting speed to in the inspector? Have you tried 0? Have you tried 0.000001? Try setting extremely small values to see if its still going straight towards it
  • Are you sure that your ball object is assigned correctly in the inspector?
  • Are there any errors in the console?
  • Are there any other scripts that are potentially affecting your AI paddle object?

Sorry for not having a concrete definitive answer, but its tough to know exactly whats wrong here without seeing a bit more of your setup. Hopefully this at least helps guide you for things to test!