Acceleration in Unity

后端 未结 4 1890
予麋鹿
予麋鹿 2021-02-20 04:38

I am trying to emulate acceleration and deceleration in Unity.

I have written to code to generate a track in Unity and place an object at a specific location on the trac

4条回答
  •  庸人自扰
    2021-02-20 05:29

    Let's define some terms first:

    1. t: interpolation variable for each spline, ranging from 0 to 1.
    2. s: the length of each spline. Depending on what type of spline you use (catmull-rom, bezier, etc.), there are formulas to calculate the estimated total length.
    3. dt: the change in t per frame. In your case, if this is constant across all the different splines, you will see sudden speed change at spline end points, as each spline has a different length s.

    The simplest way to ease the speed change at each joint is:

    void Update() {
        float dt = 0.05f; //this is currently your "global" interpolation speed, for all splines
        float v0 = s0/dt; //estimated linear speed in the first spline.
        float v1 = s1/dt; //estimated linear speed in the second spline.
        float dt0 = interpSpeed(t0, v0, v1) / s0; //t0 is the current interpolation variable where the object is at, in the first spline
        transform.position = GetCatmullRomPosition(t0 + dt0*Time.deltaTime, ...); //update your new position in first spline
    }
    

    where:

    float interpSpeed(float t, float v0, float v1, float tEaseStart=0.5f) {
        float u = (t - tEaseStart)/(1f - tEaseStart);
        return Mathf.Lerp(v0, v1, u);
    }
    

    The intuition above is that as I am reaching the end of my first spline, I predict the expected speed in the next spline, and ease my current speed to reach there.

    Finally, in order to make the easing look even better:

    • Consider using a non-linear interpolation function in interpSpeed().
    • Consider implementing an "ease-into" also at the start of the second spline

提交回复
热议问题