【问题标题】:Range bound x-axis movement范围限制 x 轴移动
【发布时间】:2022-10-06 20:45:15
【问题描述】:

我正在使用 unity/C# 并尝试制作一个将字符保持在特定 x 范围(-3 到 3)内的函数。下面是我开始工作的代码。有没有办法简化它?

//function creation to limit movement in the x axis
float rangeBoundX(int upperBound, int lowerBound, Vector3 i, float horMoveSpe = 0)
{

    //will change velocity to keep the x value in the desired range. - velocity to mvoe away from the upper bound and positive velocity goes away from the lowerBound. 

    if (i.x > upperBound)
    {
        horMoveSpe = -1;
    }

    else if (i.x < lowerBound)
    {
        horMoveSpe = 1;
    }

    return horMoveSpe;
}

\'private void FixedUpdate()\'

{
    Vector3 enemyforwardMove = transform.forward * enemySpeed * Time.fixedDeltaTime;

    Vector3 horizontalMove = transform.position;

    magn = rangeBoundX(3, -3, horizontalMove, magn);

    horizontalMove = transform.right * magn * freq;


        enemyRB.MovePosition(enemyRB.position + enemyforwardMove + horizontalMove);
}

    标签: unity3d


    【解决方案1】:

    是的,您可以使用 Math.Clamp 像这样绑定任何值。

    void update(){
           float xPos = Mathf.Clamp(transform.position.x, -3, 3);
           transform.position = new Vector3(xPos, transform.position.y, transform.position.z);
    }
    

    使用此代码,您可以水平绑定对象的位置。

    【讨论】:

      【解决方案2】:

      是的,有一种方法可以简化它。您可以使用Mathf.Clamp 方法https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html

      用法示例:float xPos = Mathf.Clamp(xValue, xMin, xMax);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多