如何将JavaScript(UnityScript)转换为C#并实现低通滤波器?

时间:2014-12-31 08:04:23

标签: javascript c# unityscript lowpass-filter

我一直在尝试将我在Unity手册中找到的低通滤波器代码示例实现到我的游戏中,但我遇到了一些问题。

以下是Unity手册中的原始JavaScript示例:

var AccelerometerUpdateInterval : float = 1.0 / 60.0;
var LowPassKernelWidthInSeconds : float = 1.0;

private var LowPassFilterFactor : float = AccelerometerUpdateInterval /    LowPassKernelWidthInSeconds; // tweakable
private var lowPassValue : Vector3 = Vector3.zero;

function Start () 
{
    lowPassValue = Input.acceleration;
}

function LowPassFilterAccelerometer() : Vector3 
{
    lowPassValue = Mathf.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor);
    return lowPassValue;
}

以下是我转换为C#:

float AccelerometerUpdateInterval = 1.0f / 60.0f;
float LowPassKernelWidthInSeconds = 1.0f;

private float LowPassFilterFactor = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds; // tweakable
private Vector3 lowPassValue = Vector3.zero;

void  Start ()
{
    lowPassValue = Input.acceleration;
}

Vector3 LowPassFilterAccelerometer ()
{
    lowPassValue = Mathf.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor);
    return lowPassValue;
}

我使用加速度计移动我的角色的原始代码就是这个(没有低通滤波器):

float speed = 30.0f;
Vector2 dir;
private float accel;

void Start () 
{
    accel = Input.acceleration.x;
}

// Update is called once per frame
void Update () 
{  
    accel = Mathf.MoveTowards (accel, Input.acceleration.x, speed * Time.deltaTime);
    dir = new Vector3(accel, 0);

    // move the object at the velocity defined in speed:
    transform.Translate(dir * speed * Time.deltaTime, 0);
}

这是我尝试实现低通滤波器以减少噪音/急动:

float AccelerometerUpdateInterval = 1.0f / 60.0f;
float LowPassKernelWidthInSeconds = 1.0f;

private float LowPassFilterFactor;
private Vector3 lowPassValue = Vector3.zero;

public float speed = 30.0f;

void Start () 
{
    lowPassValue = Input.acceleration;
    LowPassFilterFactor = AccelerometerUpdateInterval / LowPassKernelWidthInSeconds; 
}

Vector3 LowPassFilterAccelerometer() 
{
    lowPassValue = Mathf.Lerp(lowPassValue, Input.acceleration, LowPassFilterFactor);
    return lowPassValue;
}

// Update is called once per frame
void Update () 
{  
    // move the object at the velocity defined in speed:
    transform.Translate(LowPassFilterAccelerometer() * speed * Time.deltaTime, 0);
}

当我尝试编译脚本时出现了一些错误:

  

错误CS1502:最佳重载方法匹配   `UnityEngine.Mathf.Lerp(float,float,float)'有一些无效   参数

     

错误CS1503:参数#1' cannot convert UnityEngine.Vector3'   表达式以键入`float'

2 个答案:

答案 0 :(得分:1)

示例代码可能有误。请改用Vector3.Lerp()。 Lerps的完整列表是here

答案 1 :(得分:0)

错误消息告诉您需要知道的所有内容。查看UnityEngine.Mathf.Lerp(float, float, float)

的签名

您传递给它的其中一个参数不是float