如何减少我为在Unity3D中移动角色而编写的代码量?

时间:2014-07-31 05:11:58

标签: c# unity3d accelerometer performance

我正在使用Unity3D为移动平台构建一个无限的垂直平台游戏。我正在使用加速度计在屏幕上左右移动角色。到目前为止,我有这个:

if (Input.acceleration.y > -0.2f && Input.acceleration.y < 0.2f) {
                        maxSpeed = 17;
                }

        if (Input.acceleration.y > -0.5f && Input.acceleration.y < -0.2f) {
            maxSpeed = 25;
        }
        if (Input.acceleration.y > 0.2f && Input.acceleration.y < 0.5f) {
            maxSpeed = 25;
        }
        if (Input.acceleration.y > -0.7f && Input.acceleration.y < -0.5f) {
            maxSpeed = 25;
        }
        if (Input.acceleration.y > 0.5f && Input.acceleration.y < 0.9f) {
            maxSpeed = 25;
        }
        if (Input.acceleration.y < -0.9f) {
            maxSpeed = 40;
        }
        if (Input.acceleration.y  > 0.9f) {
            maxSpeed = 40;
        }

基本上,设备倾斜得越远,角色移动得越快。我非常确定有一种更好的方式来编写这段代码,但我在数学方面非常糟糕,我无法弄明白。有什么建议可以清理一下这个吗?

1 个答案:

答案 0 :(得分:1)

创建一个包含加速度限制和最大速度的类/结构。创建一个数组并添加值。然后遍历数组并检查限制是否匹配。

这样的事情:

public struct AccelerationValue {
    public float min;
    public float max;
    public int speed;

    public AccelerationValue(float mn, float mx, int s) {
        min = mn;
        max = mx;
        speed = s;
    }
}

void Start () {
    AccelerationValue[] accelerationValues = {
                                                 new AccelerationValue(-0.2f, 0.2f, 17),
                                                 new AccelerationValue(-0.5f, -0.2f, 25)
                                             };

    foreach (AccelerationValue v in accelerationValues)
    {
        if (Input.acceleration.y > v.min && Input.acceleration.y < v.max)
        {
            maxSpeed = v.speed;
        }
    }
}