0

当我倾斜手机时,我想让我的角色平稳移动。我怎样才能使它平稳移动,并且速度和速度随着手机的倾斜而增加?

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);
}
4

1 回答 1

2

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

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);
}

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

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( Mathf.Lerp( rb.velocity.x, -speed, Time.deltaTime ), 0);
    transform.eulerAngles = new Vector2(0, 180);
}

public void MoveRight()
{
    rb.velocity = new Vector2( Mathf.Lerp( rb.velocity.x, speed, Time.deltaTime ), 0);
    transform.eulerAngles = new Vector2(0, 0);
}
于 2017-04-02T20:24:34.393 回答