-1

So my goal is to move an object a certain amount of steps given towards a destination in unity. To be a bit more specific, I want to set a begin and end point for an object to move to. Then divide this distance by a certain amount of steps. And then when given users amount of steps move this amount of steps towards the end destination.

  • to give another example, say path is from A to B. Make steps of say 100 between places. Then when given 50 as input, move 50 places towards B and stay there.

I fought to do this by making waypoints in unity, but I’m new to unity so I I’m kinda stuck. Please help me :)

2 Answers2

1

I don't get your doubt, u kind of answered ur own question, having reference to both objects, let's call A and B, and then knowing that we can access this position through transform, the rest is just some math.

  • (B - A) = a line with a size equal to the distance between point A and point B but it's centered on origin

  • (B - A) / totalNumberOfSteps = the as the previous line represents our distance, let's divide it by the number of steps to get what amount of distance ONE STEP means, but this line still being centered at origin, let's call it C

  • C * currentNumberOfSteps = actual distance that it should walk, lets call it D, this one still centered at origin

  • D + A = this will give us a point in space that represents the N steps toward B from A

      private Vector3 CalculateEndPoint (Vector3 a, Vector3 b)
          => ((b - a) / totalNumberOfSteps * currentStep) + a;
    

enter image description here

Nefisto
  • 517
  • 3
  • 9
0

Of course the are many many ways to do that, given the very vague input this would be a generic animation routine for moving an object between startPoint and endPoint using the given step parameters

public static void MoveFromTo(this MonoBehaviour obj, Vector3 startPoint, Vector3 endPoint, float stepSize, int stepsToUse, float stepDuration)
{
    obj.StartCoroutine(MoveRoutine(obj.transform, startPoint, endPoint, stepSize, stepsToUse, stepDurarion)); 
}

private static IEnumerator MoveRoutine(Transform obj, Vector3 startPoint, Vector3 endPoint, float stepSize, int stepsToUse, float stepDuration)
{    
    obj.position = startPoint;

    for(var i = 0; i < stepsToUse; i++)
    {
        yield return new WaitForSeconds(stepDuration);

        obj.position = Vector3.MoveTowards(obj.position, endPoint, stepSize);  

        if(obj.position == endPoint) break;       
    }

    obj.position = endPoint;
}

Where

  • obj the object to move, will also be running the routine
  • startPoint the position to start at
  • endPoint the theoretical target position
  • stepSize how far to move per step
  • stepsToUse up to how many steps to use
  • stepDuration delay in seconds before the next step

Clamping is applied so if the endPoint is already reached with less than the given steps, no more steps are done.

derHugo
  • 83,094
  • 9
  • 75
  • 115