与前一个值相比,如何放大或放大变量值的小变化?

问题描述 投票:0回答:1

我有一个对象,其y轴的值非常微小地变化。我想放大此更改,以使其更引人注意。

我的想法是简单地比较当前值和先前值,找到差异,然后将该差异与放大系数一起添加到y轴值。这就是我想出的:

public float amplifyBy = 1.5f;
void Update()
    {
        // This calculates the center position of 4 objects and sets the transform of this object to this position
        optimalCentre = (targetAnchor1.position + targetAnchor2.position + targetAnchor3.position + targetAnchor4.position) / 4;

        // below is to amplify the y movement as there is almost no visible bounciness.
        if (optimalCentre.y != previousY)
        {
            // find difference in change
            float diff_ = previousY - optimalCentre.y;
            transform.position = new Vector3(optimalCentre.x, optimalCentre.y + (diff_ * amplifyBy), optimalCentre.z);
            Debug.Log(diff_);
        }
        else
        {
            transform.position = optimalCentre;
        }


        previousY = transform.position.y;
    }

这没有按预期方式工作,似乎正在发生的事情是,所应用的任何放大因子一直增加到无穷大,并且gameObject很快超出了范围。

谢谢

c# unity3d
1个回答
1
投票

声明一个公差值,如

const float Tolerance = 0.1f;

然后比较像

if(Math.Abs(optimalCentre.y - previousY) < Tolerance)
    {
        // find difference in change
        float diff_ = previousY - optimalCentre.y;
        transform.position = new Vector3(optimalCentre.x, optimalCentre.y + (diff_ * amplifyBy), optimalCentre.z);
        Debug.Log(diff_);
    }
© www.soinside.com 2019 - 2024. All rights reserved.