Search code examples
c#unity-game-enginegame-engine

Unity 3D Make Objects Follow Player


I am trying to make objects follow player with offset without delay on Z-axis but delayed on X-axis. When player entered a object(coin) trigger, i am adding this object to a list and i am updating each one’s position using this code. Each coin has previous and next coin that current coin follows.

{
    foreach (Coin coin in coins)
    {
        Vector3 desiredPos = new Vector3(
            coin.previous.transform.position.x,
            coin.previous.transform.position.y,
            coin.previous.transform.position.z + .15f);
            
        Vector3 smoothedPos = Vector3.Lerp(
            coin.transform.position, 
            desiredPos, 
            smoothness);
        
        coin.transform.position = smoothedPos;
    }
}

I want to get this result https://youtube.com/shorts/PHAg8Pqf0mA?feature=share

This is what i got

https://youtube.com/shorts/fzukzL_0r74?feature=share

But as you can see coins struggling some times. It is not updating their positions properly. I dont want to make it child because i need to move them on x-axis with delay.

I’ll be appreciated if you can help me.


Solution

  • You are using Vector3.Lerp which lerps all x y and z. If you want to lerp only on x axis, you should use Mathf.Lerp on the x instead:

    var x = Mathf.Lerp(x, desiredPos.x, smoothness);