0

I am making 2D unity code where I put a random x value and get a gameobject to slowly move to that position. I cant use += or -= because the number can be larger or smaller than the vector. how do I fix this? here is the code.

public IEnumerator fistthrust()
{
    float leftpos = Random.Range(-8, 8);
    float rightpos = Random.Range(-8, 8);
    while (fist.transform.position.x != leftpos && rightfist.transform.position.x != rightpos)
    {
        fist.transform.position = new Vector3(leftpos, 0, 0); -- fix these
        rightfist.transform.position = new Vector3(rightpos, 0, 0); -- 2 lines
    }
    fistscr.down();
    yield return new WaitForSeconds(0.5f);
    rfistscr.down();
    fistscr.up();
    yield return new WaitForSeconds(0.5f);
    rfistscr.up();
    fistscr.rest();
    yield return new WaitForSeconds(0.5f);
    rfistscr.rest();
}

I am a beginner game designer and have no idea what to try or what to do. Please help!!

burnsi
  • 6,194
  • 13
  • 17
  • 27
mmiv
  • 1
  • What you want to do is *interpolate* the position between the start and end. Maybe the answer to [Unity linear Interpolation for smooth 3D movement](https://stackoverflow.com/questions/67949778/unity-linear-interpolation-for-smooth-3d-movement) will help you, but now you know what term to search for if it doesn't. (In this context, lerp = linear interpolate/interpolation.) – Andrew Morton Feb 18 '23 at 18:54
  • Depends whether you want to use a fixed speed (use `MoveTowards`) or a fixed duration (use `Lerp`) – derHugo Feb 19 '23 at 19:43

1 Answers1

0

Looks like theres a MoveTowards function in the Vector3 Object https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html That should do what you want.

So something like


Vector3 currentPosition = ...;
Vector3 targetPosition = ...;

// Use Vector3.MoveTowards to move towards the target
currentPosition = Vector3.MoveTowards(currentPosition, targetPosition, 3 * Time.deltaTime);

Would move the currentPosition 3 steps towards the target position.

Then you can simply add this in a while loop or something to move it smoothly over time

JDChris100
  • 146
  • 9
  • 1
    Looking at the docs you linked to, it appears that the third parameter should be the step size, which would be (targetPosition - currentPosition) / 3 for your example here, and then that needs to be multiplied by Time.deltaTime. – Andrew Morton Feb 18 '23 at 19:16
  • Note that you still need to `yield return null;` within that `while` loop, otherwise the entire movement happens within a single frame and to the user it just appears as jumping again – derHugo Feb 19 '23 at 19:41