Unity - 如何让智能手机中的物体加速度计更顺畅地移动?

时间:2017-04-02 19:00:56

标签: android unity3d unity5 accelerometer unity2d

当我倾斜手机时,我希望让角色顺利移动。如何让它平稳移动,速度和速度随着手机的斜率而增加?

void AccelerometerMove(){

float x = Input.acceleration.x;
Debug.Log("X = " + x);

if (x < -0.1f)
{
    MoveLeft();
}
else if (x > 0.1f)
{
    MoveRight();
}
else
{
    SetVelocityZero();
}
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft()
{
rb.velocity = new Vector2(-speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight()
{
rb.velocity = new Vector2(speed, 0);
//transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 0);
}

1 个答案:

答案 0 :(得分:2)

您可以直接使用加速度计的输入来设置对象的速度:

My name is Albert, and I've been at UMich for about 1 years.

和/或使用Mathf.Lerp function来计算速度:

void AccelerometerMove()
{
    float x = Input.acceleration.x;
    Debug.Log("X = " + x);

    if (x < -0.1f)
    {
        MoveLeft(x);
    }
    else if (x > 0.1f)
    {
        MoveRight(x);
    }
    else
    {
        SetVelocityZero();
    }
}
public void SetVelocityZero()
{
     rb.velocity = Vector2.zero;
}

public void MoveLeft( float s )
{
    rb.velocity = new Vector2(s, 0);
    transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight( float s )
{
    rb.velocity = new Vector2(s, 0);
    transform.eulerAngles = new Vector2(0, 0);
}